package com.xmy.cultivate.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.ArrivalRate;
import com.xmy.cultivate.entity.views.StudentClassLogRep;
import com.xmy.cultivate.entity.views.face.FaceGetScheduling;
import com.xmy.cultivate.enums.ReachTypeEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.feign.math.IFeiMathFeignClient;
import com.xmy.cultivate.feign.physics_outside.IPhysicsFeignClient;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.ClassesNum;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.Result;
import com.xmy.cultivate.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记止课 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2022-08-10
 */
@Service
@Slf4j
public class RecordCourseServiceImpl extends ServiceImpl<RecordCourseMapper, RecordCourse> implements IRecordCourseService {

    @Autowired
    IdWorker idWorker;

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IClassRoomService iClassRoomService;

    @Autowired
    ISubjectsService iSubjectsService;

    @Autowired
    RecordCourseMapper recordCourseMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    IOrderCoursePricingService iOrderCoursePricingService;

    @Autowired
    IRecordCostService iRecordCostService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;


    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IRecordErrorService iRecordErrorService;

    @Autowired
    IStudentGradeTemporaryService iStudentGradeTemporaryService;

    @Autowired
    ICourseService iCourseService;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    IWecharsBindService iWecharsBindService;

    @Autowired
    IRecordCourseTempService iRecordCourseTempService;

    @Autowired
    @Lazy
    CoursePricingMapper coursePricingMapper;

    @Autowired
    @Lazy
    RepairCourseMapper repairCourseMapper;

    @Autowired
    @Lazy
    IRecordCourseLackService iRecordCourseLackService;

    @Autowired
    @Lazy
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    @Lazy
    RecordCourseLackMapper recordCourseLackMapper;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    CourseSchedulingDetailMapper courseSchedulingDetailMapper;

    @Autowired
    IQuarterService iQuarterService;

    final String mixDateFinal = "1970-01-01";

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    ISystemErrorLogService iSystemErrorLogService;

    @Autowired
    IStudentLeaveApplyService iStudentLeaveApplyService;

    @Autowired
    IFeiMathFeignClient iMathematicsFeignClient;

    @Autowired
    IPhysicsFeignClient iPhysicsFeignClient;

    /**
     * 批量添加记上课
     *
     * @return
     */
    @Transactional
    public boolean batchAdd(CourseSchedulingDetail courseSchedulingDetail) {

        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(courseSchedulingDetail.getId());
        if (courseSchedulingDetailInfo == null) {
            throw new CommonException(ResultCode.CourseScheduling);
        }

        List<RecordCourse> recordCourseList = new ArrayList<>();
        Iterator<RecordCourse> recordCourseIterator = courseSchedulingDetail.getRecordCourseList().iterator();
        //临时学员
        List<RecordCourseTemp> recordCourseTempList = new ArrayList<>();
        while (recordCourseIterator.hasNext()) {
            RecordCourse recordCourse = recordCourseIterator.next();
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) && recordCourse.getBuckleClassHouse() > 0) {
                Integer courseType = 1; //课程类别：1精品课（正常排课），3补课，4调课，5消课,6缺课补课
                RecordCourse recordCourseNew = this.addArriveData(courseSchedulingDetail.getId(), recordCourse.getStudentId(), recordCourse.getBuckleClassHouse(), recordCourse.getStatus(), recordCourse.getType(), courseType);
                if (recordCourseNew != null) {
                    boolean rs = this.recordAction(recordCourseNew);
                    if (rs) {
                        try {
                            iStudentGradeService.updateIsPresort(courseSchedulingDetailInfo.getSchoolId(), recordCourse.getStudentId(), courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getLessonType());
                        } catch (Exception e) {

                        }
                    }
                }

                // 删除缺课记录
                LackCourseLog lackCourseLog = courseSchedulingDetailMapper.getLackByStudentId(recordCourse.getStudentId(), courseSchedulingDetailInfo.getLessonType(), courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getLessonNum(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getYearPart());
                if (lackCourseLog != null) {
                    iLackCourseLogService.removeById(lackCourseLog.getId());
                }
            }
        }
        return true;
    }


    /**
     * 添加到课到记上课表
     *
     * @param schedulingDetailId
     * @param studentId
     * @param buckleHouse
     * @param status
     * @param type
     * @param courseType
     * @return
     */
    @Transactional
    @Override
    public RecordCourse addArriveData(Long schedulingDetailId, Long studentId, Integer buckleHouse, StatusRecordEnum status, Integer type, Integer courseType) {
        try {
            QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scheduling_detail_id", schedulingDetailId);
            queryWrapper.eq("student_id", studentId);
            queryWrapper.last("limit 1");
            RecordCourse recordCourse = recordCourseMapper.selectOne(queryWrapper);
            //已经添加过的，直接返回
            if (recordCourse != null) {
                return recordCourse;
            }

            CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(schedulingDetailId);
            if (courseSchedulingDetailInfo == null) {
                return null;
            }
            /*Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
            if(grade==null){
                return null;
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return null;
            }
            Long courseId = null;
            String courseName = "";
            if (courseSchedulingDetailInfo.getGradeId() != null){
                Course course = iCourseService.getById(courseSchedulingDetailInfo.getGradeId());
                if(course!=null){
                    courseId = course.getId();
                    courseName = course.getName();
                }
            }*/


            Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());
            //使用本学期使用课时
            Long useCount = iStudentGradeService.getStudentUseCourseCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSchoolId(), courseSchedulingDetailInfo.getSubjectsId(), studentId, courseSchedulingDetailInfo.getLessonType());

            Student student = studentMapper.selectById(studentId);
            //Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());
            recordCourse = new RecordCourse();
            recordCourse.setId(idWorker.nextId());

            recordCourse.setSchedulingDetailId(schedulingDetailId);
            recordCourse.setLessonNum(courseSchedulingDetailInfo.getLessonNum());//课次
            recordCourse.setStudentId(studentId);
            recordCourse.setStudentName(student.getName());
            recordCourse.setStatus(status);
            recordCourse.setType(type);
            recordCourse.setCourseType(courseType);
            recordCourse.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
            recordCourse.setSchoolName(courseSchedulingDetailInfo.getSchoolName());
            recordCourse.setGradeId(courseSchedulingDetailInfo.getGradeId());
            recordCourse.setGradeName(courseSchedulingDetailInfo.getGradeName());

            recordCourse.setTeacherId(courseSchedulingDetailInfo.getTeacherId());
            recordCourse.setTeacherName(courseSchedulingDetailInfo.getTeacherName());

            recordCourse.setClassRoomId(courseSchedulingDetailInfo.getClassRoomId());
            recordCourse.setClassRoomName(courseSchedulingDetailInfo.getClassRoomName());
            recordCourse.setCourseId(courseSchedulingDetailInfo.getCourseId());
            recordCourse.setCourseName(courseSchedulingDetailInfo.getCourseName());
            recordCourse.setSubjectsId(courseSchedulingDetailInfo.getSubjectsId());
            recordCourse.setSubjectsName(courseSchedulingDetailInfo.getSubjectsName());
            recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
            recordCourse.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
            recordCourse.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());
            recordCourse.setStartDateTime(LocalDateTime.parse(recordCourse.getSchoolDate() + "T" + recordCourse.getTimeStart() + ":00"));
            recordCourse.setEndDateTime(LocalDateTime.parse(recordCourse.getSchoolDate() + "T" + recordCourse.getTimeEnd() + ":00"));
            recordCourse.setYearAndQuarter(yearAndQuarter);
            recordCourse.setYearPart(courseSchedulingDetailInfo.getYearPart());
            recordCourse.setQuarter(courseSchedulingDetailInfo.getQuarter());
            recordCourse.setBuckleClassHouse(buckleHouse);

            //获取精品课最后一条数据
            StudentGrade studentGrade = iStudentGradeService.getLastForMaxId(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), 1);
            if (studentGrade != null) {
                Grade gradeOld = iGradeService.getById(studentGrade.getGradeId());
                if (gradeOld != null) {
                    recordCourse.setOldGradeId(gradeOld.getId());
                    recordCourse.setOldTeacherId(gradeOld.getTeacherId());
                    recordCourse.setYearClassId(gradeOld.getYearClassId().getKey());
                }
            }


            if (courseType.equals(4)) {
                //调课，后面补加的所以加上错误捕捉
                try {
                    CourseSchedulingDetail courseSchedulingDetailPd = iCourseSchedulingDetailService.getCourseSchedulingDetailById(courseSchedulingDetailInfo.getPid());
                    if (courseSchedulingDetailPd != null) {
                        LocalDate oldSchoolDate = courseSchedulingDetailPd.getSchoolDate();
                        recordCourse.setOldSchoolDate(oldSchoolDate);
                    }
                } catch (Exception e) {
                }
            }
            this.save(recordCourse);
            return recordCourse;
        } catch (Exception e) {
            //System.out.println("recordActionError:"+e.getMessage());
            return null;
        }
    }


    /**
     * 扣课时
     *
     * @param recordCourseParam
     * @return
     */
    @Transactional
    @Override
    public boolean recordAction(RecordCourse recordCourseParam) {

        try {
            RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseParam.getId());
            Long studentId = recordCourse.getStudentId();
            String studentName = recordCourse.getStudentName();
            Integer courseType = recordCourse.getCourseType();
            Long schedulingDetailId = recordCourse.getSchedulingDetailId();

            //QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            //queryWrapper.eq("scheduling_detail_id", schedulingDetailId);
            //queryWrapper.eq("student_id", studentId);
            //queryWrapper.eq("status", 1);
            //queryWrapper.ne("is_deduct_house", 0);//不等于未扣课时的
            //Long count = recordCourseMapper.selectCount(queryWrapper);
            //等于0
            if (recordCourse.getIsDeductHouse().equals(1)) {
                return true;
            }

            String courseTypeName = "";
            if (courseType.equals(4)) {
                courseTypeName = "(调课)";
            } else if (courseType.equals(5)) {
                courseTypeName = "(消课)";
            }

            CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(schedulingDetailId);
            if (courseSchedulingDetailInfo == null) {
                return false;
            }
            /*Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
            if(grade==null){
                return false;
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return false;
            }*/
            Long courseId = null;
            String courseName = "";
            if (courseSchedulingDetailInfo.getGradeId() != null) {
                Course course = iCourseService.getById(courseSchedulingDetailInfo.getGradeId());
                if (course != null) {
                    courseId = course.getId();
                    courseName = course.getName();
                }
            }

            //扣多少个课时===========================================================================================(备注唯一这里与自动扣课时不一样)
            Integer buckleClassHouse = 3;
            Integer teaGainHour = 3;

            Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());

            //使用本学期使用课时
            Long useCount = iStudentGradeService.getStudentUseCourseCountAllSchool(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId(), studentId, courseSchedulingDetailInfo.getLessonType());

            //状态不为消课的
            if (!courseType.equals(5)) {
                //请假，请假的不添加数据，直接返回
                //请假，请假的不添加数据，直接返回
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(recordCourse.getYearPart(), recordCourse.getQuarter());
                //0不继续扣，1继续扣
                if (quarter.getIsDeductHouse().equals(0)) {
                    if (useCount >= 45) {
                        //大于45课时，请假的不添加记录
                        //大于45课时，请假的不添加记录
                        RecordCourse recordCourseLeave = this.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
                        boolean rsBuckMoney = false;
                        if (recordCourseLeave != null) {
                            rsBuckMoney = this.greaterBuckleMoney(recordCourse, recordCourseLeave);
                        }

                        if (recordCourseLeave == null || !rsBuckMoney) {
                            UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
                            recordCourseUpdateWrapper.set("is_deduct_house", 3);
                            recordCourseUpdateWrapper.set("is_deduct_money", 3);
                            recordCourseUpdateWrapper.set("remark", "已扣15课次，不需要扣课时");
                            recordCourseUpdateWrapper.eq("id", recordCourse.getId());
                            this.update(null, recordCourseUpdateWrapper);
                            rsBuckMoney = true;
                        }

                        return rsBuckMoney;
                    }
                }
            }

            //Student student = studentMapper.selectById(studentId);

            Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());

            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(courseSchedulingDetailInfo.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType());

            if (residueCourseCount < buckleClassHouse) {

                RecordCourse recordCourseLeave = this.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
                boolean rsBuckMoney = false;
                if (recordCourseLeave != null) {
                    rsBuckMoney = this.greaterBuckleMoney(recordCourse, recordCourseLeave);
                    return rsBuckMoney;
                }

                RecordError recordError = new RecordError();
                recordError.setRecordCourseId(courseSchedulingDetailInfo.getCourseId());
                recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                recordError.setStudentId(studentId);
                recordError.setContent("此学生：" + recordCourse.getStudentName() + ",课程：" + courseSchedulingDetailInfo.getCourseName() + "剩余课时不足：" + buckleClassHouse);
                iRecordErrorService.save(recordError);
                //此学生该课程没有可用课时
                return false;
            }

            //设置是否需要改为结课
            ReadingStatusEnum readingStatusEnum = ReadingStatusEnum.IN_READING;
            //请假未补数量
            Integer lackCount = 0;
            try {
                lackCount = recordCourseMapper.getLackCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), recordCourse.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getLessonType());
            } catch (Exception e) {
            }
            if (residueCourseCount == buckleClassHouse && lackCount.equals(0)) {
                readingStatusEnum = ReadingStatusEnum.FINISH;
            }

            List<OrderDetail> orderDetailList = orderDetailMapper.orderDetailListForSubjects(courseSchedulingDetailInfo.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType());

            Integer diffClassHosue = buckleClassHouse;//还差多少课时

            Integer teaGainHourAll = 0;//老师得课时总课时
            BigDecimal teaGainMoneyAll = new BigDecimal(0);

            BigDecimal buckleClassMoneyAll = new BigDecimal(0);
            BigDecimal buckleClassHourAll = new BigDecimal(0);

            //老师课时获得金额
            BigDecimal courseInMoney = staff.getCourseInMoney();
            BigDecimal courseInCount = new BigDecimal(staff.getCourseInCount());
            if (courseInCount.compareTo(new BigDecimal(0)) <= 0) {
                return false;
            }

            iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourse.getId()));//先删除详情
            Long lastOrderDetailId = null;
            for (OrderDetail orderDetail : orderDetailList) {
                if (diffClassHosue == 0) {
                    continue;
                }

                CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
                if (coursePricing == null) {
                    //此学生数据异常
                    RecordError recordError = new RecordError();
                    recordError.setRecordCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                    recordError.setStudentId(studentId);
                    recordError.setContent("此学生课程价格数据异常：" + orderDetail.getCoursePriceId());
                    iRecordErrorService.save(recordError);
                    continue;
                }

                Integer userClassHouse = 0;//本次使用课时
                //本次要扣的课时大于等于剩余课时
                if (diffClassHosue > orderDetail.getResidueCourseCount()) {
                    userClassHouse = orderDetail.getResidueCourseCount();
                    diffClassHosue = diffClassHosue - orderDetail.getResidueCourseCount();
                } else {
                    userClassHouse = diffClassHosue;
                    diffClassHosue = 0;
                }

                RecordCost recordCost = new RecordCost();
                recordCost.setId(idWorker.nextId());
                recordCost.setRecordCourseId(recordCourse.getId());
                recordCost.setOrderDetailId(orderDetail.getId());
                lastOrderDetailId = orderDetail.getId();

                /**
                 * 本次使用金额 = 扣课时金额 + 服务费 + 材料费
                 */
                BigDecimal buckleClassMoneyOther = new BigDecimal("0");

                //本次扣多少个课时
                BigDecimal stuDeductHour = new BigDecimal(userClassHouse);
                //学生此次扣课时使用金额
                BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));

                buckleClassMoneyOther = buckleClassMoneyOther.add(buckleClassMoney);

                /**
                 * compareTo 反回1 表示大于，0等于，-1小于
                 * 如果此次扣除金额大于剩余金额，则改为使用剩余金额
                 */

                //缺课未补的金额
                BigDecimal lackMoney = iRecordCourseLackService.getAllBucklemoneyForOrderDetailId(orderDetail.getId());
                BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                if (residuePrice.compareTo(BigDecimal.ZERO) < 0)
                    residuePrice = new BigDecimal(0);
                if (userClassHouse == orderDetail.getResidueCourseCount()) {
                    //使用可是等于剩余课时
                    buckleClassMoney = residuePrice;
                    buckleClassMoneyOther = buckleClassMoney;
                } else if (buckleClassMoneyOther.compareTo(residuePrice) > 0) {
                    if (lackMoney.compareTo(BigDecimal.ZERO) > 0) {
                        if (residuePrice.subtract(lackMoney).compareTo(buckleClassMoney) > 0) {
                            buckleClassMoney = residuePrice.subtract(lackMoney);
                        } else {
                            if (residuePrice.compareTo(buckleClassMoney) < 0) {
                                buckleClassMoney = residuePrice;
                            }
                        }
                    } else {
                        //本次使用金额大于剩余金额
                        buckleClassMoney = residuePrice;
                    }
                    buckleClassMoneyOther = buckleClassMoney;
                }

                buckleClassHourAll = buckleClassHourAll.add(stuDeductHour);
                buckleClassMoneyAll = buckleClassMoneyAll.add(buckleClassMoney);

                //BigDecimal teaGainHour = new BigDecimal(grade.getTeaGainHour());//班级上一节课，老师得课时
                //BigDecimal teaGainMoney = teaGainHour.divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                recordCost.setBuckleClassHouse(userClassHouse);

                Integer teacherGetClassHosue = (userClassHouse / 3) * teaGainHour;//教师得多少课时

                //BigDecimal teaGainMoney = new BigDecimal(teacherGetClassHosue).divide(courseInCount, BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);
                BigDecimal teaGainMoney = new BigDecimal(0);
                //镇级
                if (recordCourse.getSchoolId() != null && recordCourse.getSchoolId().equals(1697088501396127745L)) {
                    teaGainMoney = new BigDecimal(17);
                } else {
                    teaGainMoney = new BigDecimal(20);
                }

                teaGainHourAll = teaGainHourAll + teacherGetClassHosue;
                teaGainMoneyAll = teaGainMoneyAll.add(teaGainMoney);
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额
                    recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                    recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额
                }
                //全新订单里的使用课时，剩余课时，剩余金额，使用金额
                /**
                 使用课时：use_course_count
                 上课累计使用金额：use_price
                 剩余课时：residue_course_count
                 剩余金额：residue_price
                 */
                //扣课时
                //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                Integer useCourseCountForOrder = orderDetail.getUseCourseCount() + userClassHouse;
                orderDetail.setUseCourseCount(useCourseCountForOrder);//累计使用课时

                Integer residueCourseCountForUse = orderDetail.getResidueCourseCount() - userClassHouse;
                orderDetail.setResidueCourseCount(residueCourseCountForUse);//剩余课时
                //到课
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
                    orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                }
                iOrderDetailService.updateById(orderDetail);

                //UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
                //recordCostUpdateWrapper.eq("id",recordCost.getId());
                iRecordCostService.save(recordCost);

                //更新分班里使用的课时
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                studentGradeQueryWrapper.eq("status", 1);
                studentGradeQueryWrapper.eq("deleted", 0);
                studentGradeQueryWrapper.eq("lesson_type", courseSchedulingDetailInfo.getLessonType());
                studentGradeQueryWrapper.eq("reading_status", 1);
                //studentGradeQueryWrapper.eq("grade_id",courseSchedulingDetailInfo.getGradeId());
                studentGradeQueryWrapper.last("limit 1");
                StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                if (studentGrade == null) {
                    studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(courseSchedulingDetailInfo.getSchoolId(), orderDetail.getStudentId(), courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getLessonType());
                }

                if (studentGrade != null) {
                    Integer useCourseCount = studentGrade.getUseCourseCount() + userClassHouse;//累计使用课时
                    studentGrade.setUseCourseCount(useCourseCount);
                    studentGrade.setReadingStatus(readingStatusEnum);
                    iStudentGradeService.updateById(studentGrade);
                    recordCourse.setStudentGradeId(studentGrade.getId());
                }
                if (readingStatusEnum.getKey().equals(5)) {
                    studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
                    studentGradeQueryWrapper.eq("student_id", orderDetail.getStudentId());
                    studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
                    studentGradeQueryWrapper.ne("status", 2);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.eq("reading_status", 1);
                    studentGradeQueryWrapper.orderByDesc("created_at");
                    List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGradeUpdate : studentGradeList) {
                        studentGradeUpdate.setReadingStatus(readingStatusEnum);
                        iStudentGradeService.updateById(studentGradeUpdate);
                    }

                }
            }
            recordCourse.setBuckleClassHouse(Integer.parseInt(buckleClassHourAll.toString()));
            recordCourse.setOrderDetailId(lastOrderDetailId);
            recordCourse.setIsDeductHouse(1);
            //到课
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                recordCourse.setTeacherGetMoney(teaGainMoneyAll);
                recordCourse.setIsDeductMoney(1);
            } else {
                recordCourse.setIsDeductMoney(0);
            }

            recordCourse.setDeductType(2);//扣课时方式，0未知，1自动，2是手动

            //UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
            //recordCourseUpdateWrapper.eq("scheduling_detail_id",schedulingDetailId);
            //recordCourseUpdateWrapper.eq("student_id",recordCourse.getStudentId());
            this.updateById(recordCourse);

            if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                //缺课的金额暂时保存
                RecordCourseLack recordCourseLack = new RecordCourseLack();
                recordCourseLack.setId(recordCourse.getId());
                recordCourseLack.setOrderDetailId(recordCourse.getOrderDetailId());
                recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
                recordCourseLack.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourseLack.setTeacherGetHouse(teaGainHourAll);
                recordCourseLack.setTeacherGetMoney(teaGainMoneyAll);
                iRecordCourseLackService.saveOrUpdate(recordCourseLack);
            }

            //到课，发送微信提醒
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("course_status", 1);//课时是否异常，异常的不推送家长,正常：1
            Long courseStatusCount = iStudentGradeService.count(studentGradeQueryWrapper);
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                if (courseStatusCount > 0) {
                    StringBuilder first = new StringBuilder();
                    first.append(courseSchedulingDetailInfo.getGradeName()).append("(").append(courseSchedulingDetailInfo.getSchoolName()).append(")").append("新增上课记录，请查看");
                    String keyword1 = studentName;
                    StringBuilder keyword2 = new StringBuilder();
                    keyword2.append(courseSchedulingDetailInfo.getSchoolDate()).append(" ").append(courseSchedulingDetailInfo.getTimeStart()).append("-").append(courseSchedulingDetailInfo.getTimeEnd());
                    StringBuilder keyword3 = new StringBuilder();
                    keyword3.append("考勤状态为“上课" + courseTypeName + "”，消耗").append(buckleClassHouse).append("课时");

                    Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;//剩余课时
                    StringBuilder keyword4 = new StringBuilder();
                    keyword4.append(residueCourseCountNew).append("课时").append(",如有疑问请及时与老师联系");
                    //StringBuilder remark = new StringBuilder();
                    //remark.append("考勤状态为“上课"+courseTypeName+"”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());
                    try {
                        iWecharsBindService.useCourseHouse(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), keyword4.toString(), "", courseSchedulingDetailInfo.getId() + "" + studentId);
                    } catch (Exception e) {

                    }
                }
            }
            return true;
        } catch (Exception e) {
            //System.out.println("recordActionError:"+e.getMessage());
            return false;
        }
    }


    @Override
    public Result tryListenBuckleHouse(RecordCourse recordCourse) {
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("year_part", recordCourse.getYearPart());
        recordCourseQueryWrapper.eq("quarter", recordCourse.getQuarter());
        recordCourseQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
        recordCourseQueryWrapper.eq("student_id", recordCourse.getStudentId());
        recordCourseQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
        recordCourseQueryWrapper.eq("lesson_num", 1);
        recordCourseQueryWrapper.eq("check_type", 1);
        Long count = this.count(recordCourseQueryWrapper);
        if (count > 0) {
            return new Result(Code.ERROR, "", "第1次课已上，试听核对失败");
        }

        StudentGrade studentGradeLast = iStudentGradeService.getLastForMaxId(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), recordCourse.getLessonType());
        if (studentGradeLast != null) {
            Grade grade = iGradeService.getById(studentGradeLast.getGradeId());
            if (grade != null) {
                Course course = iCourseService.getById(grade.getCourseId());
                Staff staff = iStaffService.getById(grade.getTeacherId());
                Staff staffClass = iStaffService.getById(recordCourse.getCreatedId());
                recordCourse.setGradeId(grade.getId());
                recordCourse.setOldTeacherId(staff.getId());
                recordCourse.setTeacherId(staffClass.getId());
                recordCourse.setTeacherName(staffClass.getName());
                recordCourse.setOldGradeId(grade.getId());
                recordCourse.setGradeName(grade.getName());
                recordCourse.setYearClassId(grade.getYearClassId().getKey());
                recordCourse.setCourseId(course.getId());
                recordCourse.setCourseName(course.getName());
                QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
                courseSchedulingDetailQueryWrapper.eq("grade_id", grade.getId());
                courseSchedulingDetailQueryWrapper.eq("lesson_num", 1);
                courseSchedulingDetailQueryWrapper.last("limit 1");
                CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getOne(courseSchedulingDetailQueryWrapper);
                if (courseSchedulingDetail != null) {
                    recordCourse.setSchedulingDetailId(courseSchedulingDetail.getId());
                    recordCourse.setLessonNum(courseSchedulingDetail.getLessonNum());
                }
                this.updateById(recordCourse);
            }
            boolean rs = this.recordAction(recordCourse);
            if (rs) {
                return new Result(Code.OK, "", "核对成功");
            } else {
                return new Result(Code.ERROR, "", "核对失败");
            }
        } else {
            return new Result(Code.ERROR, "", "未分班，不能核对");
        }
    }


    @Override
    public RecordCourse getLeaveData(Integer yearPart,
                                     Integer quarterNum,
                                     Integer lessonType,
                                     Long studentId,
                                     Long subjectsId) {
        return recordCourseMapper.getLeaveData(yearPart, quarterNum, lessonType, studentId, subjectsId);
    }

    /**
     * 大于15次课的，扣除补课金额
     *
     * @return
     */
    @Override
    public boolean greaterBuckleMoney(RecordCourse recordCourse, RecordCourse recordCourseOld) {

        if (recordCourse.getIsDeductHouse().equals(1))
            return false;

        //已扣过的，不再扣
        if (recordCourseOld.getIsDeductMoney().equals(1)) {
            return false;
        }

        RecordCourseLack recordCourseLack = recordCourseLackMapper.selectById(recordCourseOld.getId());
        if (recordCourseLack == null)
            return false;

        OrderDetail orderDetail = orderDetailMapper.selectById(recordCourseLack.getOrderDetailId());
        if (orderDetail == null)
            return false;

        BigDecimal buckleClassMoney = recordCourseLack.getBuckleClassMoney();
        if (orderDetail.getResiduePrice().compareTo(recordCourseLack.getBuckleClassMoney()) < 0) {
            buckleClassMoney = orderDetail.getResiduePrice();
        }

        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));//剩余金额
        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
        orderDetailMapper.updateById(orderDetail);

        //更新记录
        recordCourse.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCourse.setStudentGradeId(recordCourseOld.getStudentGradeId());
        recordCourse.setCourseType(3);
        recordCourse.setIsDeductHouse(1);
        recordCourse.setIsDeductMoney(1);
        recordCourse.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().add(buckleClassMoney));
        recordCourse.setTeacherGetMoney(recordCourse.getTeacherGetMoney().add(recordCourseLack.getTeacherGetMoney()));
        recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCourse.setByRecordId(recordCourseOld.getId());//被补课id
        recordCourseMapper.updateById(recordCourse);

        //更新原来的数据
        recordCourseOld.setBuckleClassHouse(0);
        recordCourseOld.setBuckleClassMoney(new BigDecimal(0));
        recordCourseOld.setTeacherGetHouse(0);
        recordCourseOld.setTeacherGetMoney(new BigDecimal(0));
        recordCourseOld.setIsRepair(1);
        recordCourseOld.setIsDeductHouse(1);
        recordCourseOld.setIsDeductMoney(1);
        recordCourseOld.setStatus(StatusRecordEnum.LEAVE);//请假
        recordCourseMapper.updateById(recordCourseOld);

        /*UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
        recordCostUpdateWrapper.set("buckle_class_house",0);
        recordCostUpdateWrapper.eq("record_course_id",recordCourseOld.getId());
        iRecordCostService.update(null,recordCostUpdateWrapper);*/
        //删除原来的数据
        iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourseOld.getId()));

        //添加记录详情
        RecordCost recordCostNew = new RecordCost();
        //BeanUtils.copyProperties(recordCostOld,recordCostNew);
        recordCostNew.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCostNew.setBuckleClassMoney(buckleClassMoney);
        recordCostNew.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
        recordCostNew.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCostNew.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCostNew.setId(idWorker.nextId());
        recordCostNew.setRecordCourseId(recordCourse.getId());
        iRecordCostService.save(recordCostNew);

        recordCourseLack.setIsDeductMoney(1);
        recordCourseLackMapper.updateById(recordCourseLack);
        //Map<String,Object> objectMap = new HashMap<>();
        //objectMap.put("buckleHouse",recordCourse.getBuckleClassHouse());
        //objectMap.put("buckleMoney",recordCourse.getBuckleClassMoney());

        Integer leaveCount = recordCourseMapper.getLeaveCount(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
        Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(recordCourse.getSchoolId(), recordCourse.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getYearAndQuarter(), recordCourse.getLessonType());

        if (leaveCount.equals(0) && residueCourseCount.equals(0)) {
            UpdateWrapper<StudentGrade> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("year_part", recordCourse.getYearPart());
            updateWrapper.eq("quarter_num", recordCourse.getQuarter());
            updateWrapper.eq("student_id", recordCourse.getStudentId());
            updateWrapper.eq("subjects_id", recordCourse.getSubjectsId());
            updateWrapper.eq("reading_status", 1);
            updateWrapper.set("reading_status", 5);//结课
            iStudentGradeService.update(updateWrapper);
        }

        return true;
    }


    /**
     * 上满15次课的，手动消课
     *
     * @param recordCourseParam
     * @return
     */
    @Transactional
    public Result recordActionConsume(RecordCourse recordCourseParam) {

        try {
            RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseParam.getId());
            Long studentId = recordCourse.getStudentId();
            String studentName = recordCourse.getStudentName();
            Integer courseType = recordCourse.getCourseType();
            Long schedulingDetailId = recordCourse.getSchedulingDetailId();

            Long useCouseCount = iStudentGradeService.getStudentUseCourseCountAllSchool(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), recordCourse.getLessonType());
            if (useCouseCount < 45) {
                throw new CommonException(ResultCode.NOT_FIFTEEN_USE_COUNSE);
            }

            //不等于0
            if (recordCourse.getIsDeductHouse().equals(1)) {
                return new Result(Code.ERROR, "", "已扣过课时，不要重复扣课时");
            }

            String courseTypeName = "";
            if (courseType.equals(4)) {
                courseTypeName = "(调课)";
            } else if (courseType.equals(5)) {
                courseTypeName = "(消课)";
            }

            CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(schedulingDetailId);
            if (courseSchedulingDetailInfo == null) {
                courseSchedulingDetailInfo = new CourseSchedulingDetail();
                RepairCourse repairCourse = repairCourseMapper.selectById(schedulingDetailId);
                if (repairCourse != null) {
                    BeanUtils.copyProperties(repairCourse, courseSchedulingDetailInfo);
                    Grade gradeOld = iGradeService.getById(repairCourse.getOldGradeId());
                    Course course = null;
                    if (gradeOld != null) {
                        course = iCourseService.getById(gradeOld.getCourseId());
                        if (course != null) {
                            courseSchedulingDetailInfo.setCourseId(course.getId());
                            courseSchedulingDetailInfo.setCourseName(course.getName());
                            courseSchedulingDetailInfo.setSubjectsId(course.getSubjectsId());
                        }
                        if (courseSchedulingDetailInfo.getGradeId() == null) {
                            courseSchedulingDetailInfo.setGradeId(gradeOld.getId());
                            courseSchedulingDetailInfo.setGradeName(gradeOld.getName());
                        }
                    }
                } else {
                    return new Result(Code.ERROR, "", "排课信息不存在");
                }
            }
            /*Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
            if(grade==null){
                return false;
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return false;
            }*/
            Long courseId = null;
            String courseName = "";
            if (courseSchedulingDetailInfo.getGradeId() != null) {
                Course course = iCourseService.getById(courseSchedulingDetailInfo.getGradeId());
                if (course != null) {
                    courseId = course.getId();
                    courseName = course.getName();
                }
            }

            //扣多少个课时===========================================================================================(备注唯一这里与自动扣课时不一样)
            Integer buckleClassHouse = 3;
            Integer teaGainHour = 3;

            Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());

            //使用本学期使用课时
            //Long useCount = iStudentGradeService.getStudentUseCourseCount(courseSchedulingDetailInfo.getYearPart(),courseSchedulingDetailInfo.getQuarter(),courseSchedulingDetailInfo.getSchoolId(),courseSchedulingDetailInfo.getSubjectsId(),studentId,courseSchedulingDetailInfo.getLessonType());

            //状态不为消课的
            /*if (!courseType.equals(5)){
                //请假，请假的不添加数据，直接返回
                if (useCount >=45){
                    //大于45课时，请假的不添加记录
                    return true;
                }
            }*/

            //Student student = studentMapper.selectById(studentId);

            Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());

            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(courseSchedulingDetailInfo.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType());

            if (residueCourseCount < buckleClassHouse) {
                RecordError recordError = new RecordError();
                recordError.setRecordCourseId(courseSchedulingDetailInfo.getCourseId());
                recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                recordError.setStudentId(studentId);
                recordError.setContent("此学生：" + recordCourse.getStudentName() + ",课程：" + courseSchedulingDetailInfo.getCourseName() + "剩余课时不足：" + buckleClassHouse);
                iRecordErrorService.save(recordError);
                //此学生该课程没有可用课时
                return new Result(Code.ERROR, "", "此学生该课程没有可用课时");
            }

            //设置是否需要改为结课
            ReadingStatusEnum readingStatusEnum = ReadingStatusEnum.IN_READING;
            //请假未补数量
            Integer lackCount = 0;
            try {
                lackCount = recordCourseMapper.getLackCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), recordCourse.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getLessonType());
            } catch (Exception e) {
            }
            if (residueCourseCount == buckleClassHouse && lackCount.equals(0)) {
                readingStatusEnum = ReadingStatusEnum.FINISH;
            }

            List<OrderDetail> orderDetailList = orderDetailMapper.orderDetailListForSubjects(courseSchedulingDetailInfo.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType());

            Integer diffClassHosue = buckleClassHouse;//还差多少课时

            Integer teaGainHourAll = 0;//老师得课时总课时
            BigDecimal teaGainMoneyAll = new BigDecimal(0);

            BigDecimal buckleClassMoneyAll = new BigDecimal(0);
            BigDecimal buckleClassHourAll = new BigDecimal(0);

            //老师课时获得金额
            BigDecimal courseInMoney = staff.getCourseInMoney();
            BigDecimal courseInCount = new BigDecimal(3);
            //if (courseInCount.compareTo(new BigDecimal(0)) <= 0) {
            //    return new Result(Code.ERROR,"","");
            //}

            iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourse.getId()));//先删除详情
            Long lastOrderDetailId = null;
            for (OrderDetail orderDetail : orderDetailList) {
                if (diffClassHosue == 0) {
                    continue;
                }

                CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
                if (coursePricing == null) {
                    //此学生数据异常
                    RecordError recordError = new RecordError();
                    recordError.setRecordCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                    recordError.setStudentId(studentId);
                    recordError.setContent("此学生课程价格数据异常：" + orderDetail.getCoursePriceId());
                    iRecordErrorService.save(recordError);
                    continue;
                }

                Integer userClassHouse = 0;//本次使用课时
                //本次要扣的课时大于等于剩余课时
                if (diffClassHosue > orderDetail.getResidueCourseCount()) {
                    userClassHouse = orderDetail.getResidueCourseCount();
                    diffClassHosue = diffClassHosue - orderDetail.getResidueCourseCount();
                } else {
                    userClassHouse = diffClassHosue;
                    diffClassHosue = 0;
                }

                RecordCost recordCost = new RecordCost();
                recordCost.setId(idWorker.nextId());
                recordCost.setRecordCourseId(recordCourse.getId());
                recordCost.setOrderDetailId(orderDetail.getId());
                lastOrderDetailId = orderDetail.getId();

                /**
                 * 本次使用金额 = 扣课时金额 + 服务费 + 材料费
                 */
                BigDecimal buckleClassMoneyOther = new BigDecimal("0");

                //本次扣多少个课时
                BigDecimal stuDeductHour = new BigDecimal(userClassHouse);
                //学生此次扣课时使用金额
                BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));

                buckleClassMoneyOther = buckleClassMoneyOther.add(buckleClassMoney);

                /**
                 * compareTo 反回1 表示大于，0等于，-1小于
                 * 如果此次扣除金额大于剩余金额，则改为使用剩余金额
                 */

                //缺课未补的金额
                BigDecimal lackMoney = iRecordCourseLackService.getAllBucklemoneyForOrderDetailId(orderDetail.getId());
                BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                if (residuePrice.compareTo(BigDecimal.ZERO) < 0)
                    residuePrice = new BigDecimal(0);
                if (userClassHouse == orderDetail.getResidueCourseCount()) {
                    if (lackMoney.compareTo(BigDecimal.ZERO) > 0) {
                        if (residuePrice.subtract(lackMoney).compareTo(buckleClassMoney) > 0) {
                            buckleClassMoney = residuePrice.subtract(lackMoney);
                        } else {
                            if (residuePrice.compareTo(buckleClassMoney) < 0) {
                                buckleClassMoney = residuePrice;
                            }
                        }
                    } else {
                        //使用可是等于剩余课时
                        buckleClassMoney = residuePrice;
                    }
                    buckleClassMoneyOther = buckleClassMoney;

                } else if (buckleClassMoneyOther.compareTo(residuePrice) > 0) {
                    //本次使用金额大于剩余金额
                    buckleClassMoney = residuePrice;
                    buckleClassMoneyOther = buckleClassMoney;
                }

                buckleClassHourAll = buckleClassHourAll.add(stuDeductHour);
                buckleClassMoneyAll = buckleClassMoneyAll.add(buckleClassMoney);

                //BigDecimal teaGainHour = new BigDecimal(grade.getTeaGainHour());//班级上一节课，老师得课时
                //BigDecimal teaGainMoney = teaGainHour.divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                recordCost.setBuckleClassHouse(userClassHouse);

                Integer teacherGetClassHosue = (userClassHouse / 3) * teaGainHour;//教师得多少课时

                //BigDecimal teaGainMoney = new BigDecimal(teacherGetClassHosue).divide(courseInCount, BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);
                BigDecimal teaGainMoney = new BigDecimal(0);
                //镇级
                if (recordCourse.getSchoolId() != null && recordCourse.getSchoolId().equals(1697088501396127745L)) {
                    teaGainMoney = new BigDecimal(17);
                } else {
                    teaGainMoney = new BigDecimal(20);
                }
                teaGainHourAll = teaGainHourAll + teacherGetClassHosue;
                teaGainMoneyAll = teaGainMoneyAll.add(teaGainMoney);
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额
                    recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                    recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额
                }
                //全新订单里的使用课时，剩余课时，剩余金额，使用金额
                /**
                 使用课时：use_course_count
                 上课累计使用金额：use_price
                 剩余课时：residue_course_count
                 剩余金额：residue_price
                 */
                //扣课时
                //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                Integer useCourseCountForOrder = orderDetail.getUseCourseCount() + userClassHouse;
                orderDetail.setUseCourseCount(useCourseCountForOrder);//累计使用课时

                Integer residueCourseCountForUse = orderDetail.getResidueCourseCount() - userClassHouse;
                orderDetail.setResidueCourseCount(residueCourseCountForUse);//剩余课时
                //到课
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
                    orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                }
                iOrderDetailService.updateById(orderDetail);

                //UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
                //recordCostUpdateWrapper.eq("id",recordCost.getId());
                iRecordCostService.save(recordCost);

                //更新分班里使用的课时
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                studentGradeQueryWrapper.eq("status", 1);
                studentGradeQueryWrapper.eq("deleted", 0);
                studentGradeQueryWrapper.eq("lesson_type", courseSchedulingDetailInfo.getLessonType());
                studentGradeQueryWrapper.eq("reading_status", 1);
                //studentGradeQueryWrapper.eq("grade_id",courseSchedulingDetailInfo.getGradeId());
                studentGradeQueryWrapper.last("limit 1");
                StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                if (studentGrade == null) {
                    studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(courseSchedulingDetailInfo.getSchoolId(), orderDetail.getStudentId(), courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getLessonType());
                }

                if (studentGrade != null) {
                    Integer useCourseCount = studentGrade.getUseCourseCount() + userClassHouse;//累计使用课时
                    studentGrade.setUseCourseCount(useCourseCount);
                    studentGrade.setReadingStatus(readingStatusEnum);
                    iStudentGradeService.updateById(studentGrade);
                    recordCourse.setStudentGradeId(studentGrade.getId());
                }
                if (readingStatusEnum.getKey().equals(5)) {
                    studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
                    studentGradeQueryWrapper.eq("student_id", orderDetail.getStudentId());
                    studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
                    studentGradeQueryWrapper.ne("status", 2);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.eq("reading_status", 1);
                    studentGradeQueryWrapper.orderByDesc("created_at");
                    List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGradeUpdate : studentGradeList) {
                        studentGradeUpdate.setReadingStatus(readingStatusEnum);
                        iStudentGradeService.updateById(studentGradeUpdate);
                    }

                }
            }
            recordCourse.setBuckleClassHouse(Integer.parseInt(buckleClassHourAll.toString()));
            recordCourse.setOrderDetailId(lastOrderDetailId);
            recordCourse.setIsDeductHouse(1);
            recordCourse.setRemark("满15次后，消课扣课时");
            //到课
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                recordCourse.setTeacherGetMoney(teaGainMoneyAll);
                recordCourse.setIsDeductMoney(1);
            } else {
                recordCourse.setIsDeductMoney(0);
            }

            recordCourse.setDeductType(3);//扣课时方式，0未知，1自动，2是手动3满15次后按消课扣课时

            //UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
            //recordCourseUpdateWrapper.eq("scheduling_detail_id",schedulingDetailId);
            //recordCourseUpdateWrapper.eq("student_id",recordCourse.getStudentId());
            this.updateById(recordCourse);

            if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                //缺课的金额暂时保存
                RecordCourseLack recordCourseLack = new RecordCourseLack();
                recordCourseLack.setId(recordCourse.getId());
                recordCourseLack.setOrderDetailId(recordCourse.getOrderDetailId());
                recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
                recordCourseLack.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourseLack.setTeacherGetHouse(teaGainHourAll);
                recordCourseLack.setTeacherGetMoney(teaGainMoneyAll);
                iRecordCourseLackService.saveOrUpdate(recordCourseLack);
            }

            //到课，发送微信提醒
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("course_status", 1);//课时是否异常，异常的不推送家长,正常：1
            Long courseStatusCount = iStudentGradeService.count(studentGradeQueryWrapper);
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                if (courseStatusCount > 0) {
                    StringBuilder first = new StringBuilder();
                    first.append(courseSchedulingDetailInfo.getGradeName()).append("(").append(courseSchedulingDetailInfo.getSchoolName()).append(")").append("新增上课记录，请查看");
                    String keyword1 = studentName;
                    StringBuilder keyword2 = new StringBuilder();
                    keyword2.append(courseSchedulingDetailInfo.getSchoolDate()).append(" ").append(courseSchedulingDetailInfo.getTimeStart()).append("-").append(courseSchedulingDetailInfo.getTimeEnd());
                    StringBuilder keyword3 = new StringBuilder();
                    keyword3.append("考勤状态为“上课" + courseTypeName + "”，消耗").append(buckleClassHouse).append("课时");

                    Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;//剩余课时
                    StringBuilder keyword4 = new StringBuilder();
                    keyword4.append(residueCourseCountNew).append("课时").append(",如有疑问请及时与老师联系");
                    //StringBuilder remark = new StringBuilder();
                    //remark.append("考勤状态为“上课"+courseTypeName+"”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());
                    try {
                        iWecharsBindService.useCourseHouse(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), keyword4.toString(), "", courseSchedulingDetailInfo.getId() + "" + studentId);
                    } catch (Exception e) {

                    }
                }
            }
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("buckleHouse", recordCourse.getBuckleClassHouse());
            objectMap.put("buckleMoney", recordCourse.getBuckleClassMoney());
            return new Result(Code.OK, objectMap, "");
        } catch (Exception e) {
            //System.out.println("recordActionError:"+e.getMessage());
            return new Result(Code.ERROR, "", e.getMessage());
        }
    }

    /**
     * 取消消课
     *
     * @param recordCourse
     * @return
     */
    @Transactional
    @Override
    public Boolean resetRecordConsume(RecordCourse recordCourse) {
        QueryWrapper<RecordCost> recordCostQueryWrapper = new QueryWrapper<>();
        recordCostQueryWrapper.eq("record_course_id", recordCourse.getId());
        List<RecordCost> recordCostList = iRecordCostService.list(recordCostQueryWrapper);
        boolean isDelete = false;
        int delCount = 0;
        for (RecordCost recordCost : recordCostList) {
            OrderDetail orderDetail = iOrderDetailService.getById(recordCost.getOrderDetailId());
            if (orderDetail != null) {
                orderDetail.setUseCourseCount(orderDetail.getUseCourseCount() - recordCost.getBuckleClassHouse());
                orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + recordCost.getBuckleClassHouse());

                BigDecimal userPrice = orderDetail.getUsePrice().subtract(recordCost.getBuckleClassMoney());
                if (userPrice.compareTo(BigDecimal.ZERO) < 0) {
                    userPrice = new BigDecimal(0);
                }
                orderDetail.setUsePrice(userPrice);

                BigDecimal residuePrice = orderDetail.getResiduePrice().add(recordCost.getBuckleClassMoney());
                if (residuePrice.compareTo(orderDetail.getSolidPrice()) > 0) {
                    residuePrice = orderDetail.getSolidPrice();
                }
                orderDetail.setResiduePrice(residuePrice);
                iOrderDetailService.updateById(orderDetail);

                StudentGrade studentGrade = iStudentGradeService.getById(recordCourse.getStudentGradeId());
                if (studentGrade != null) {
                    Integer useCourseCount = studentGrade.getUseCourseCount() - recordCost.getBuckleClassHouse();//使用课时
                    studentGrade.setUseCourseCount(useCourseCount);
                    if (studentGrade.getReadingStatus().getKey().equals(5) || studentGrade.getReadingStatus().getKey().equals(6)) {
                        studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
                    }
                    iStudentGradeService.updateById(studentGrade);
                } else {
                    /**
                     * 以下是暂时的
                     */
                    //更新分班里使用的课时
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                    //studentGradeQueryWrapper.eq("reading_status",1);
                    studentGradeQueryWrapper.eq("grade_id", recordCourse.getGradeId());
                    studentGradeQueryWrapper.last("limit 1");
                    studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    if (studentGrade == null) {
                        studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(recordCourse.getSchoolId(), orderDetail.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType());
                    }
                    if (studentGrade != null) {
                        Integer useCourseCount = studentGrade.getUseCourseCount() - recordCost.getBuckleClassHouse();//使用课时
                        studentGrade.setUseCourseCount(useCourseCount);
                        if (studentGrade.getReadingStatus().getKey().equals(5) || studentGrade.getReadingStatus().getKey().equals(6)) {
                            studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
                        }
                        iStudentGradeService.updateById(studentGrade);
                    }
                }
                isDelete = true;
            }
            iRecordCostService.removeById(recordCost.getId());
        }


        recordCourse.setRemark("已扣15课次，不需要扣课时");
        recordCourse.setBuckleClassMoney(new BigDecimal(0));
        recordCourse.setBuckleClassHouse(0);
        recordCourse.setIsDeductHouse(3);
        recordCourse.setIsDeductMoney(3);
        recordCourse.setDeductType(1);
        this.updateById(recordCourse);
        return true;
    }


    /**
     * 补课，调课，消课，缺课--补课扣课时
     *
     * @param recordCourseParam
     * @return
     */
    @Transactional
    @Override
    public boolean recordActionRepair(RecordCourse recordCourseParam) {

        try {
            RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseParam.getId());
            if (recordCourse.getIsDeductHouse().equals(1)) {
                return true;
            }

            Long studentId = recordCourse.getStudentId();
            String studentName = recordCourse.getStudentName();
            Integer courseType = recordCourse.getCourseType();
            Long repairId = recordCourse.getSchedulingDetailId();
            Long schoolId = recordCourse.getSchoolId();
            Long subjectsId = recordCourse.getSubjectsId();

            RepairCourse repairCourseInfo = repairCourseMapper.selectById(repairId);
            if (repairCourseInfo == null) {
                return false;
            }
            String courseTypeName = "";
            if (courseType.equals(4)) {
                courseTypeName = "(调课)";
            } else if (courseType.equals(5)) {
                courseTypeName = "(消课)";
            } else if (courseType.equals(6)) {
                courseTypeName = "(缺课补课)";
            }
            Integer buckleClassHouse = 3;
            Integer teaGainHour = 3;

            /*Grade grade = iGradeService.getById(repairCourseInfo.getGradeId());
            if(grade==null){
                return false;
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return false;
            }*/
            Long courseId = null;
            String courseName = "";
            if (repairCourseInfo.getGradeId() != null) {
                Course course = iCourseService.getById(repairCourseInfo.getGradeId());
                if (course != null) {
                    courseId = course.getId();
                    courseName = course.getName();
                }
            }

            //调课，缺课补课的大于45课时的不扣课时
            if (!courseType.equals(5)) {
                //请假，请假的不添加数据，直接返回
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(recordCourse.getYearPart(), recordCourse.getQuarter());
                //0不继续扣，1继续扣
                if (quarter.getIsDeductHouse().equals(0)) {
                    //请假
                    //本学期使用课程
                    Long useCount = iStudentGradeService.getStudentUseCourseCountAllSchool(repairCourseInfo.getYearPart(), repairCourseInfo.getQuarter(), repairCourseInfo.getSubjectsId(), studentId, repairCourseInfo.getLessonType());
                    if (useCount >= 45) {
                        //大于45课时，请假的不添加记录
                        RecordCourse recordCourseLeave = this.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
                        boolean rsBuckMoney = false;
                        if (recordCourseLeave != null) {
                            rsBuckMoney = this.greaterBuckleMoney(recordCourse, recordCourseLeave);
                        }
                        if (recordCourseLeave == null || !rsBuckMoney) {
                            UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
                            recordCourseUpdateWrapper.set("is_deduct_house", 3);
                            recordCourseUpdateWrapper.set("is_deduct_money", 3);
                            recordCourseUpdateWrapper.set("remark", "已扣15课次，不需要扣课时");
                            recordCourseUpdateWrapper.eq("id", recordCourse.getId());
                            this.update(null, recordCourseUpdateWrapper);
                        }
                        return rsBuckMoney;
                    }
                }
            }

            QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scheduling_detail_id", repairId);
            queryWrapper.eq("student_id", studentId);
            queryWrapper.eq("status", 1);
            queryWrapper.ne("is_deduct_house", 0);
            Long count = recordCourseMapper.selectCount(queryWrapper);
            Student student = studentMapper.selectById(studentId);
            if (!recordCourse.getIsDeductHouse().equals(0)) {
                return true;
            }

            Organization organizationInfo = iOrganizationService.getById(repairCourseInfo.getSchoolId());
            String schoolName = "";
            if (organizationInfo != null) {
                schoolName = organizationInfo.getName();
            }

            Staff staff = iStaffService.getById(repairCourseInfo.getTeacherId());

            Integer yearAndQuarter = Integer.parseInt(repairCourseInfo.getYearPart() + "" + repairCourseInfo.getQuarter());

            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourseInfo.getSchoolId(), studentId, repairCourseInfo.getSubjectsId(), yearAndQuarter, repairCourseInfo.getLessonType());

            if (residueCourseCount < buckleClassHouse) {
                RecordCourse recordCourseLeave = this.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
                boolean rsBuckMoney = false;
                if (recordCourseLeave != null) {
                    rsBuckMoney = this.greaterBuckleMoney(recordCourse, recordCourseLeave);
                    return rsBuckMoney;
                }


                RecordError recordError = new RecordError();
                recordError.setRecordCourseId(repairCourseInfo.getGradeId());
                recordError.setCourseId(courseId);
                recordError.setSchoolId(repairCourseInfo.getSchoolId());
                recordError.setStudentId(studentId);
                recordError.setContent("调课、消课、缺课补课，此学生：" + student.getName() + ",课程：" + courseName + "剩余课时不足：" + buckleClassHouse);
                iRecordErrorService.save(recordError);
                //此学生该课程没有可用课时
                return false;
            }

            //设置是否需要改为结课
            ReadingStatusEnum readingStatusEnum = ReadingStatusEnum.IN_READING;
            //请假未补数量
            Integer lackCount = 0;
            try {
                lackCount = recordCourseMapper.getLackCount(repairCourseInfo.getYearPart(), repairCourseInfo.getQuarter(), repairCourseInfo.getSchoolId(), studentId, repairCourseInfo.getSubjectsId(), repairCourseInfo.getLessonType());
            } catch (Exception e) {
            }
            if (residueCourseCount == buckleClassHouse && lackCount.equals(0)) {
                readingStatusEnum = ReadingStatusEnum.FINISH;
            }

            List<OrderDetail> orderDetailList = orderDetailMapper.orderDetailListForSubjects(repairCourseInfo.getSchoolId(), studentId, repairCourseInfo.getSubjectsId(), yearAndQuarter, repairCourseInfo.getLessonType());

            Integer diffClassHosue = buckleClassHouse;//还差多少课时

            Integer teaGainHourAll = 0;//老师得课时总课时
            BigDecimal teaGainMoneyAll = new BigDecimal(0);

            BigDecimal buckleClassMoneyAll = new BigDecimal(0);
            BigDecimal buckleClassHourAll = new BigDecimal(0);


            if (recordCourse == null) {
                recordCourse = new RecordCourse();
                //设置id
                //Long recordCourseId = idWorker.nextId();
                recordCourse.setId(idWorker.nextId());
            }

            //老师课时获得金额
            BigDecimal courseInMoney = staff.getCourseInMoney();
            BigDecimal courseInCount = new BigDecimal(staff.getCourseInCount());
            if (courseInCount.compareTo(new BigDecimal(0)) <= 0) {
                return false;
            }

            iRecordCostService.removeById(recordCourse.getId());//先删除详情
            Long lastOrderDetailId = null;
            for (OrderDetail orderDetail : orderDetailList) {
                if (diffClassHosue == 0) {
                    continue;
                }
                CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
                if (coursePricing == null) {
                    //此学生数据异常
                    RecordError recordError = new RecordError();
                    recordError.setRecordCourseId(courseId);
                    recordError.setCourseId(courseId);
                    recordError.setSchoolId(repairCourseInfo.getSchoolId());
                    recordError.setStudentId(studentId);
                    recordError.setContent("此学生课程价格数据异常：" + orderDetail.getCoursePriceId());
                    iRecordErrorService.save(recordError);
                    continue;
                }

                Integer userClassHouse = 0;//本次使用课时
                //本次要扣的课时大于等于剩余课时
                if (diffClassHosue > orderDetail.getResidueCourseCount()) {
                    userClassHouse = orderDetail.getResidueCourseCount();
                    diffClassHosue = diffClassHosue - orderDetail.getResidueCourseCount();
                } else {
                    userClassHouse = diffClassHosue;
                    diffClassHosue = 0;
                }

                RecordCost recordCost = new RecordCost();
                recordCost.setId(idWorker.nextId());
                recordCost.setRecordCourseId(recordCourse.getId());
                recordCost.setOrderDetailId(orderDetail.getId());

                lastOrderDetailId = orderDetail.getId();

                /**
                 * 本次使用金额 = 扣课时金额 + 服务费 + 材料费
                 */
                BigDecimal buckleClassMoneyOther = new BigDecimal("0");

                //本次扣多少个课时
                BigDecimal stuDeductHour = new BigDecimal(userClassHouse);
                //学生此次扣课时使用金额
                BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));

                buckleClassMoneyOther = buckleClassMoneyOther.add(buckleClassMoney);

                //缺课未补的金额
                BigDecimal lackMoney = iRecordCourseLackService.getAllBucklemoneyForOrderDetailId(orderDetail.getId());
                BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                if (residuePrice.compareTo(BigDecimal.ZERO) < 0)
                    residuePrice = new BigDecimal(0);

                /**
                 * compareTo 反回1 表示大于，0等于，-1小于
                 * 如果此次扣除金额大于剩余金额，则改为使用剩余金额
                 */
                if (userClassHouse == orderDetail.getResidueCourseCount()) {
                    if (lackMoney.compareTo(BigDecimal.ZERO) > 0) {
                        if (residuePrice.subtract(lackMoney).compareTo(buckleClassMoney) > 0) {
                            buckleClassMoney = residuePrice.subtract(lackMoney);
                        } else {
                            if (residuePrice.compareTo(buckleClassMoney) < 0) {
                                buckleClassMoney = residuePrice;
                            }
                        }
                    } else {
                        //本次使用金额大于剩余金额
                        buckleClassMoney = residuePrice;
                    }
                    buckleClassMoneyOther = buckleClassMoney;
                } else if (buckleClassMoneyOther.compareTo(residuePrice) > 0) {
                    //本次使用金额大于剩余金额
                    buckleClassMoney = residuePrice;
                    buckleClassMoneyOther = buckleClassMoney;
                } else if (orderDetail.getResidueCourseCount().compareTo(buckleClassHouse) == 0) {
                    if (lackMoney.compareTo(BigDecimal.ZERO) > 0) {
                        if (residuePrice.subtract(lackMoney).compareTo(buckleClassMoney) > 0) {
                            buckleClassMoney = residuePrice.subtract(lackMoney);
                        }
                    } else {
                        //本次使用金额大于剩余金额
                        buckleClassMoney = residuePrice;
                    }
                    buckleClassMoneyOther = buckleClassMoney;
                }
                buckleClassHourAll = buckleClassHourAll.add(stuDeductHour);
                buckleClassMoneyAll = buckleClassMoneyAll.add(buckleClassMoney);

                //BigDecimal teaGainHour = new BigDecimal(grade.getTeaGainHour());//班级上一节课，老师得课时
                //BigDecimal teaGainMoney = teaGainHour.divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                recordCost.setBuckleClassHouse(userClassHouse);

                Integer teacherGetClassHosue = (userClassHouse / 3) * teaGainHour;//教师得多少课时

                //BigDecimal teaGainMoney = new BigDecimal(teacherGetClassHosue).divide(courseInCount, BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                BigDecimal teaGainMoney = new BigDecimal(0);
                //镇级
                if (recordCourse.getSchoolId() != null && recordCourse.getSchoolId().equals(1697088501396127745L)) {
                    teaGainMoney = new BigDecimal(17);
                } else {
                    teaGainMoney = new BigDecimal(20);
                }

                teaGainHourAll = teaGainHourAll + teacherGetClassHosue;
                teaGainMoneyAll = teaGainMoneyAll.add(teaGainMoney);
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额
                    recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                    recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额
                }

                //全新订单里的使用课时，剩余课时，剩余金额，使用金额
                /**
                 使用课时：use_course_count
                 上课累计使用金额：use_price
                 剩余课时：residue_course_count
                 剩余金额：residue_price
                 */
                //扣课时
                //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                Integer useCourseCountForOrder = orderDetail.getUseCourseCount() + userClassHouse;
                orderDetail.setUseCourseCount(useCourseCountForOrder);//累计使用课时

                Integer residueCourseCountForUse = orderDetail.getResidueCourseCount() - userClassHouse;
                orderDetail.setResidueCourseCount(residueCourseCountForUse);//剩余课时
                //到课
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
                    orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                }

                iOrderDetailService.updateById(orderDetail);

                //UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
                //recordCostUpdateWrapper.eq("id",recordCost.getId());
                iRecordCostService.save(recordCost);

                //更新分班里使用的课时
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                studentGradeQueryWrapper.eq("status", 1);
                studentGradeQueryWrapper.eq("deleted", 0);
                studentGradeQueryWrapper.eq("reading_status", 1);
                studentGradeQueryWrapper.eq("grade_id", repairCourseInfo.getGradeId());
                studentGradeQueryWrapper.last("limit 1");
                StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                if (studentGrade == null) {
                    studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(schoolId, orderDetail.getStudentId(), subjectsId, recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType());
                }

                if (studentGrade != null) {
                    Integer useCourseCount = studentGrade.getUseCourseCount() + userClassHouse;//使用课时
                    studentGrade.setUseCourseCount(useCourseCount);
                    if (readingStatusEnum.equals(ReadingStatusEnum.FINISH)) {
                        studentGrade.setReadingStatus(readingStatusEnum);
                    }
                    iStudentGradeService.updateById(studentGrade);
                    recordCourse.setStudentGradeId(studentGrade.getId());
                }

            }
            recordCourse.setBuckleClassHouse(Integer.parseInt(buckleClassHourAll.toString()));
            recordCourse.setOrderDetailId(lastOrderDetailId);
            recordCourse.setIsDeductHouse(1);
            //到课
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                recordCourse.setTeacherGetMoney(teaGainMoneyAll);
                recordCourse.setIsDeductMoney(1);
            } else {
                recordCourse.setIsDeductMoney(0);
            }

            recordCourse.setDeductType(1);//扣课时方式，0未知，1自动，2是手动
            recordCourse.setRemark("");

            //UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
            //recordCourseUpdateWrapper.eq("scheduling_detail_id",schedulingDetailId);
            //recordCourseUpdateWrapper.eq("student_id",recordCourse.getStudentId());

            if (courseType.equals(4)) {
                //调课，后面补加的所以加上错误捕捉
                try {
                    CourseSchedulingDetail courseSchedulingDetailPd = iCourseSchedulingDetailService.getCourseSchedulingDetailById(repairCourseInfo.getOutSchedulingDetailId());
                    if (courseSchedulingDetailPd != null) {
                        LocalDate oldSchoolDate = courseSchedulingDetailPd.getSchoolDate();
                        recordCourse.setOldSchoolDate(oldSchoolDate);
                    }
                } catch (Exception e) {
                }
            }

            //获取精品课最后一次排课
            StudentGrade studentGradeLast = iStudentGradeService.getLastOne(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), 1);
            if (studentGradeLast != null) {
                recordCourse.setOldGradeId(studentGradeLast.getGradeId());
                Grade gradeLast = iGradeService.getById(studentGradeLast.getGradeId());
                if (gradeLast != null) {
                    recordCourse.setOldTeacherId(gradeLast.getTeacherId());
                    recordCourse.setYearClassId(gradeLast.getYearClassId().getKey());
                }
            }


            this.updateById(recordCourse);
            //recordCourseList.add(recordCourse);

            if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                //缺课的金额暂时保存
                RecordCourseLack recordCourseLack = new RecordCourseLack();
                recordCourseLack.setId(recordCourse.getId());
                recordCourseLack.setOrderDetailId(recordCourse.getOrderDetailId());
                recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
                recordCourseLack.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourseLack.setTeacherGetHouse(teaGainHourAll);
                recordCourseLack.setTeacherGetMoney(teaGainMoneyAll);
                iRecordCourseLackService.saveOrUpdate(recordCourseLack);
            }

            //到课，发送微信提醒
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id", repairCourseInfo.getSchoolId());
            studentGradeQueryWrapper.eq("student_id", student.getId());
            studentGradeQueryWrapper.eq("subjects_id", repairCourseInfo.getSubjectsId());
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("course_status", 1);//课时是否异常，异常的不推送家长,正常：1

            Long courseStatusCount = iStudentGradeService.count(studentGradeQueryWrapper);
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                if (courseStatusCount > 0) {
                    StringBuilder first = new StringBuilder();
                    first.append(repairCourseInfo.getGradeName()).append("(").append(schoolName).append(")").append("新增上课记录，请查看");
                    String keyword1 = student.getName();
                    StringBuilder keyword2 = new StringBuilder();
                    keyword2.append(repairCourseInfo.getSchoolDate()).append(" ").append(repairCourseInfo.getTimeStart()).append("-").append(repairCourseInfo.getTimeEnd());
                    StringBuilder remark = new StringBuilder();
                    //Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;
                    //remark.append("考勤状态为“上课"+courseTypeName+"”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");
                    StringBuilder keyword3 = new StringBuilder();
                    keyword3.append("考勤状态为“上课" + courseTypeName + "”，消耗").append(buckleClassHouse).append("课时");
                    Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;//剩余课时
                    StringBuilder keyword4 = new StringBuilder();
                    keyword4.append(residueCourseCountNew).append("课时").append(",如有疑问请及时与老师联系");
                    //StringBuilder remark = new StringBuilder();
                    //remark.append("考勤状态为“上课"+courseTypeName+"”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());
                    try {
                        iWecharsBindService.useCourseHouse(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), keyword4.toString(), "", recordCourse.getId() + "" + studentId);
                    } catch (Exception e) {

                    }
                }
            }
            return true;
        } catch (Exception e) {
            //System.out.println("recordActionError:"+e.getMessage());
            return false;
        }
    }

    /**
     * 缺课学生补课扣除金额
     *
     * @param repairCourseId 按排的补课id
     * @return
     */
    @Override
    @Transactional
    public boolean repairBuckleMoney(Long repairCourseId) {

        //获取出按排的补课信息
        RepairCourse repairCourse = repairCourseMapper.selectById(repairCourseId);
        if (repairCourse == null)
            return false;
        //缺课记上课记录
        RecordCourse recordCourseOld = recordCourseMapper.selectById(repairCourse.getRecordCourseId());
        if (recordCourseOld == null)
            return false;
        /*if (recordCourseOld.getTeacherGetMoney().compareTo(BigDecimal.ZERO) == 0){
            return false;
        }*/

        //获取出记上课信息
        RecordCourse recordCourse = recordCourseMapper.selectOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
        //已扣过的，不再扣
        if (recordCourseOld.getIsDeductMoney().equals(1)) {
            return true;
        }
        if (recordCourse == null)
            return false;
        if (recordCourse.getCourseType() != 3)
            return false;

        RecordCourseLack recordCourseLack =  recordCourseLackMapper.selectById(recordCourseOld.getId());
        if (recordCourseLack == null)
            return false;

        OrderDetail orderDetail = iOrderDetailService.getById(recordCourseLack.getOrderDetailId());
        if (orderDetail == null)
            return false;

        BigDecimal buckleClassMoney = recordCourseLack.getBuckleClassMoney();
        if (orderDetail.getResiduePrice().compareTo(recordCourseLack.getBuckleClassMoney()) < 0) {
            buckleClassMoney = orderDetail.getResiduePrice();
        }

        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));//剩余金额
        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
        iOrderDetailService.updateById(orderDetail);

        //更新记录
        recordCourse.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCourse.setStudentGradeId(recordCourseOld.getStudentGradeId());
        recordCourse.setIsDeductHouse(1);
        recordCourse.setIsDeductMoney(1);
        recordCourse.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().add(buckleClassMoney));
        recordCourse.setTeacherGetMoney(recordCourse.getTeacherGetMoney().add(recordCourseLack.getTeacherGetMoney()));
        recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCourseMapper.updateById(recordCourse);

        //更新原来的数据
        recordCourseOld.setBuckleClassHouse(0);
        recordCourseOld.setBuckleClassMoney(new BigDecimal(0));
        recordCourseOld.setTeacherGetHouse(0);
        recordCourseOld.setTeacherGetMoney(new BigDecimal(0));
        recordCourseOld.setIsRepair(1);
        recordCourseOld.setIsDeductHouse(1);
        recordCourseOld.setIsDeductMoney(1);
        recordCourseOld.setStatus(StatusRecordEnum.LEAVE);//请假
        //recordCourseOld.setRepairEndDateTime(repairCourse.getEndDateTime());
        recordCourseMapper.updateById(recordCourseOld);

        /*UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
        recordCostUpdateWrapper.set("buckle_class_house",0);
        recordCostUpdateWrapper.eq("record_course_id",recordCourseOld.getId());
        iRecordCostService.update(null,recordCostUpdateWrapper);*/
        //删除原来的数据
        iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourseOld.getId()));

        //添加记录详情
        RecordCost recordCostNew = new RecordCost();
        //BeanUtils.copyProperties(recordCostOld,recordCostNew);
        recordCostNew.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCostNew.setBuckleClassMoney(buckleClassMoney);
        recordCostNew.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
        recordCostNew.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCostNew.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCostNew.setId(idWorker.nextId());
        recordCostNew.setRecordCourseId(recordCourse.getId());
        iRecordCostService.save(recordCostNew);

        recordCourseLack.setIsDeductMoney(1);
        recordCourseLackMapper.updateById(recordCourseLack);

        //安排补课的数据设置为已补课状态（已扣课时）
        repairCourse.setStatus(1);
        repairCourseMapper.updateById(repairCourse);

        return true;
    }


    /**
     * 大于15次课的，扣除补课金额
     *
     * @param recordCourseId
     * @param byRecordId
     * @return
     */
    @Override
    @Transactional
    public boolean greaterBuckleMoney(Long recordCourseId, Long byRecordId) {

        //缺课记上课记录
        RecordCourse recordCourseOld = recordCourseMapper.selectById(byRecordId);
        if (recordCourseOld == null)
            return false;
        /*if (recordCourseOld.getTeacherGetMoney().compareTo(BigDecimal.ZERO) == 0){
            return false;
        }*/

        //获取出记上课信息
        RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseId);
        //已扣过的，不再扣
        if (recordCourseOld.getIsDeductMoney().equals(1)) {
            return true;
        }
        if (recordCourse == null)
            return false;
        if (recordCourse.getCourseType() != 3)
            return false;

        RecordCourseLack recordCourseLack = recordCourseLackMapper.selectById(recordCourseOld.getId());
        if (recordCourseLack == null)
            return false;

        OrderDetail orderDetail = iOrderDetailService.getById(recordCourseLack.getOrderDetailId());
        if (orderDetail == null)
            return false;

        BigDecimal buckleClassMoney = recordCourseLack.getBuckleClassMoney();
        if (orderDetail.getResiduePrice().compareTo(recordCourseLack.getBuckleClassMoney()) < 0) {
            buckleClassMoney = orderDetail.getResiduePrice();
        }

        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));//剩余金额
        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
        iOrderDetailService.updateById(orderDetail);

        //更新记录
        recordCourse.setByRecordId(recordCourseOld.getId());
        recordCourse.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCourse.setStudentGradeId(recordCourseOld.getStudentGradeId());
        recordCourse.setIsDeductHouse(1);
        recordCourse.setIsDeductMoney(1);
        recordCourse.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().add(buckleClassMoney));
        recordCourse.setTeacherGetMoney(recordCourse.getTeacherGetMoney().add(recordCourseLack.getTeacherGetMoney()));
        recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCourseMapper.updateById(recordCourse);

        //更新原来的数据
        recordCourseOld.setBuckleClassHouse(0);
        recordCourseOld.setBuckleClassMoney(new BigDecimal(0));
        recordCourseOld.setTeacherGetHouse(0);
        recordCourseOld.setTeacherGetMoney(new BigDecimal(0));
        recordCourseOld.setIsRepair(1);
        recordCourseOld.setIsDeductHouse(1);
        recordCourseOld.setIsDeductMoney(1);
        recordCourseOld.setStatus(StatusRecordEnum.LEAVE);//请假
        recordCourseMapper.updateById(recordCourseOld);

        /*UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
        recordCostUpdateWrapper.set("buckle_class_house",0);
        recordCostUpdateWrapper.eq("record_course_id",recordCourseOld.getId());
        iRecordCostService.update(null,recordCostUpdateWrapper);*/
        //删除原来的数据
        iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourseOld.getId()));

        //添加记录详情
        RecordCost recordCostNew = new RecordCost();
        //BeanUtils.copyProperties(recordCostOld,recordCostNew);
        recordCostNew.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCostNew.setBuckleClassMoney(buckleClassMoney);
        recordCostNew.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
        recordCostNew.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCostNew.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCostNew.setId(idWorker.nextId());
        recordCostNew.setRecordCourseId(recordCourse.getId());
        iRecordCostService.save(recordCostNew);

        recordCourseLack.setIsDeductMoney(1);
        recordCourseLackMapper.updateById(recordCourseLack);

        return true;
    }


    /**
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @return
     */
    public boolean deductClassHours(Long schoolId, Long studentId, Long subjectsId) {
        return true;
    }

    /**
     * @param courseSchedulingDetailId
     * @param studentId
     * @param studentName
     * @param type                     1排课班级里的学员，2临时学员，3补课学员
     * @param courseType               1精品课（正常排课），3补课，4调课，5消课
     * @param reachTypeEnum
     * @param siginInTeacherId         签到老师id
     * @return
     */
    @Override
    public Long addForSchedulingId(Long courseSchedulingDetailId, Long studentId, String studentName, Integer type, Integer courseType, ReachTypeEnum reachTypeEnum, Long siginInTeacherId, LocalDateTime dateTimeNow, Integer signType, String schoolSiteId) {
        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(courseSchedulingDetailId);
        if (courseSchedulingDetailInfo == null) {
            courseSchedulingDetailInfo = new CourseSchedulingDetail();
        }

        Grade oldGrade = new Grade();//精品课所在班级（按日程排课）
        Long recordCourseId = null;
        //补课学生、调课、消课、缺课补课
        if (courseType.equals(3) || courseType.equals(4) || courseType.equals(5) || courseType.equals(6) || courseType.equals(9)) {
            RepairCourse repairCourseInfo = repairCourseMapper.selectById(courseSchedulingDetailId);
            if (repairCourseInfo != null) {
                BeanUtils.copyProperties(repairCourseInfo, courseSchedulingDetailInfo);
                recordCourseId = repairCourseInfo.getRecordCourseId();
            }
        }
        Grade grade = null;
        if (courseSchedulingDetailInfo.getGradeId() != null) {
            grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
        }
        if (grade == null) {
            grade = new Grade();
        }

        //精品课所在班级（按日程排课,没有班级，要添加上精品课所在班级）
        StudentGrade studentGrade = iStudentGradeService.getLastForMaxId(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId(), studentId, 1);
        if (studentGrade != null) {
            oldGrade = iGradeService.getById(studentGrade.getGradeId());
            if (oldGrade == null) {
                oldGrade = new Grade();
                oldGrade.setId(studentGrade.getGradeId());
            }
        }


        RecordCourse recordCourse = new RecordCourse();
        if (reachTypeEnum != null) {
            //recordCourse.setReachType(reachTypeEnum);
        } else {
            //recordCourse.setReachType(ReachTypeEnum.NORMAL);
        }

        recordCourse.setStudentId(studentId);
        recordCourse.setStudentName(studentName);
        recordCourse.setStatus(StatusRecordEnum.REACH);
        recordCourse.setType(type);
        if (courseType.equals(3)) {
            if (recordCourseId != null) {
                RecordCourse recordCourseOld = recordCourseMapper.selectById(recordCourseId);
                if (recordCourseOld != null) {
                    recordCourseOld.setIsRepair(1);
                    recordCourseMapper.updateById(recordCourseOld);
                }
            }
        } else if (courseType.equals(6)) {
            //缺课补课
            if (recordCourseId != null) {
                LackCourseLog lackCourseLog = iLackCourseLogService.getById(recordCourseId);
                if (lackCourseLog != null) {
                    lackCourseLog.setIsRepair(1);
                    iLackCourseLogService.updateById(lackCourseLog);
                }
            }
        }

        //recordCourse.setReachType(ReachTypeEnum.NORMAL);
        recordCourse.setCourseType(courseType);

        //签到老师
        Long teacherId = siginInTeacherId;
        if (teacherId == null) {
            teacherId = courseSchedulingDetailInfo.getTeacherId();
        }
        //不是精品课
        if (courseSchedulingDetailInfo.getLessonType() != null) {
            //不是精品课
            if (!courseSchedulingDetailInfo.getLessonType().equals(1)) {
                try {
                    //Integer notPassCount = recordCourseMapper.getNotPassCount(courseSchedulingDetailInfo.getYearPart(),courseSchedulingDetailInfo.getQuarter(),studentId,LocalDate.now().toString(),LocalDateTime.now().withNano(0).toString(),courseSchedulingDetailInfo.getLessonType(),courseSchedulingDetailInfo.getSubjectsId(),tastMaxLessonNum);
                    Integer notPassCount = 1;
                    if (courseSchedulingDetailInfo.getSubjectsId().equals(1L)) {
                        //智能或者刷题课，已通关算为临时的
                        notPassCount = recordCourseMapper.getNotPassCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), studentId, LocalDate.now().toString(), LocalDateTime.now().withNano(0).toString(), courseSchedulingDetailInfo.getLessonType(), courseSchedulingDetailInfo.getSubjectsId(), 30);
                    } else {
                        Integer tastMaxLessonNum = this.getMaxTaskLesson(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId().toString(), 1676874588501311488L, 1);
                        //获取出精品课所在班级，年级和班型使用
                        StudentGrade studentGradeBoutique = iStudentGradeService.getLastOne(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId(), studentId, 1);
                        if (!Objects.isNull(studentGradeBoutique)) {
                            //数学和物理
                            notPassCount = recordCourseMapper.getNotPassCountMath(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId(), studentId, studentGradeBoutique.getYearClassId(), studentGradeBoutique.getClassTypeIdNew(), LocalDateTime.now().withNano(0).toString(), tastMaxLessonNum);
                        }
                    }
                    if (notPassCount == 0) {
                        recordCourse.setCourseType(7);//临时
                    }
                } catch (Exception e) {
                }
            }
            //teacherId = courseSchedulingDetailInfo.getTeacherId();
        }


        //老师
        recordCourse.setTeacherId(teacherId);
        Staff staff = iStaffService.getById(teacherId);
        if (staff == null) {
            //throw new CommonException(ResultCode.TeacerNo);
        }
        //if(staff.getIsTeacher()!=1){
        //throw new CommonException(ResultCode.NotATeacher);
        //}
        if (staff != null) {
            recordCourse.setTeacherName(staff.getName());
        }


        recordCourse.setSchedulingDetailId(courseSchedulingDetailInfo.getId());//排课id
        //校区
        recordCourse.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
        Organization organization = iOrganizationService.getById(courseSchedulingDetailInfo.getSchoolId());
        if (organization != null) {
            recordCourse.setSchoolName(organization.getName());
        }

        //班级
        /*if (courseSchedulingDetailInfo.getGradeId() != null) {
            recordCourse.setGradeId(courseSchedulingDetailInfo.getGradeId());
            recordCourse.setGradeName(courseSchedulingDetailInfo.getGradeName());
        } else {
            recordCourse.setGradeId(oldGrade.getId());
            recordCourse.setGradeName(oldGrade.getName());
        }*/
        recordCourse.setGradeId(grade.getId());
        recordCourse.setGradeName(grade.getName());
        recordCourse.setOldGradeId(oldGrade.getId());
        recordCourse.setOldTeacherId(oldGrade.getTeacherId());
        if (oldGrade.getYearClassId() != null) {
            recordCourse.setYearClassId(oldGrade.getYearClassId().getKey());
        }

        //Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());

        /*if(grade==null){
            //throw new CommonException(ResultCode.CourseSchedulingClassNo);
            //recordCourse.setTeacherGetHouse(grade.getStuDeductHour());//等确定
        }
        Course course = iCourseService.getById(grade.getCourseId());
        if(course==null){
            //throw new CommonException(ResultCode.COURSE_NOT);
        }*/

        Long courseId = null;
        String courseName = "";
        if (courseSchedulingDetailInfo.getGradeId() != null) {
            Course course = iCourseService.getById(courseSchedulingDetailInfo.getGradeId());
            if (course != null) {
                courseId = course.getId();
                courseName = course.getName();
            }
        }


        //年份与月份
        Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());
        recordCourse.setLessonType(courseSchedulingDetailInfo.getLessonType());
        recordCourse.setLessonNum(courseSchedulingDetailInfo.getLessonNum());//课次
        recordCourse.setYearAndQuarter(yearAndQuarter);
        recordCourse.setCourseId(courseId);
        recordCourse.setCourseName(courseName);
        recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
        //recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
        recordCourse.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
        recordCourse.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());
        recordCourse.setStartDateTime(courseSchedulingDetailInfo.getStartDateTime());
        recordCourse.setEndDateTime(courseSchedulingDetailInfo.getEndDateTime());

        //教室
        recordCourse.setClassRoomId(courseSchedulingDetailInfo.getClassRoomId());
        ClassRoom classRoom = iClassRoomService.getById(courseSchedulingDetailInfo.getClassRoomId());
        if (classRoom != null) {
            recordCourse.setClassRoomName(classRoom.getName());
        }
        //科目
        recordCourse.setSubjectsId(courseSchedulingDetailInfo.getSubjectsId());
        Subjects subjects = iSubjectsService.getById(courseSchedulingDetailInfo.getSubjectsId());
        if (subjects != null) {
            recordCourse.setSubjectsName(subjects.getName());
        }
        recordCourse.setYearPart(courseSchedulingDetailInfo.getYearPart());
        recordCourse.setQuarter(courseSchedulingDetailInfo.getQuarter());
        //1精品课（正常排课），3补课，4调课，5消课
        if (courseType.equals(5)) {
            //recordCourse.setBuckleClassHouse(grade.getStuDeductHour());
            //recordCourse.setTeacherGetHouse(grade.getTeaGainHour());
        }
        //1精品课（正常排课），3补课，4调课，5消课
        if (courseType.equals(1) || courseType.equals(4) || courseType.equals(6) || courseType.equals(9)) {
            /*QueryWrapper<RecordCourse> studentGradeQueryWrapper = new QueryWrapper<>();
            //studentGradeQueryWrapper.eq("school_id",);//包含所有校区
            studentGradeQueryWrapper.eq("year_part",grade.getYearPart());
            studentGradeQueryWrapper.eq("quarter",course.getQuarterNum());
            studentGradeQueryWrapper.eq("subjects_id",course.getSubjectsId());
            studentGradeQueryWrapper.eq("student_id",studentId);
            studentGradeQueryWrapper.eq("is_deduct_house",1);
            studentGradeQueryWrapper.ge("buckle_class_house",3);
            //studentGradeQueryWrapper.ne("status",2);
            studentGradeQueryWrapper.eq("deleted",0);
            Long useCount = iStudentGradeService.getStudentUseCourseCount(grade.getYearPart(),course.getQuarterNum(),grade.getSchoolId(),course.getSubjectsId(),studentId);
            //是否大于15次课
            if (useCount < 45){
                recordCourse.setBuckleClassHouse(grade.getStuDeductHour());
                recordCourse.setTeacherGetHouse(grade.getTeaGainHour());
            }else {
                //如果已经扣课时再签退，会改变状态，故多加判断
                QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                recordCourseQueryWrapper.eq("scheduling_detail_id",courseSchedulingDetailId);
                recordCourseQueryWrapper.eq("student_id",studentId);
                recordCourseQueryWrapper.last("limit 1");
                RecordCourse recordCourseDe = this.getOne(recordCourseQueryWrapper);
                if (recordCourseDe == null){
                    recordCourse.setIsDeductHouse(3);//已到15课次，不需要扣
                    recordCourse.setRemark("已到15课次，不需要扣课时");
                }
            }*/
        }
        /*UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
        recordCourseUpdateWrapper.eq("scheduling_detail_id",courseSchedulingDetailId);
        recordCourseUpdateWrapper.eq("student_id",studentId);
        this.saveOrUpdate(recordCourse,recordCourseUpdateWrapper);*/

        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("scheduling_detail_id", courseSchedulingDetailId);
        recordCourseQueryWrapper.eq("student_id", studentId);
        recordCourseQueryWrapper.last("limit 1");
        RecordCourse recordCourseOld = this.getOne(recordCourseQueryWrapper);
        if (recordCourseOld != null) {
            recordCourse.setId(recordCourseOld.getId());
            //还未按排补课的
            if (recordCourseOld.getIsRepair() != null && recordCourseOld.getIsRepair().equals(0)) {
                //请假类型，还未扣金额的改为到课
                if (recordCourseOld.getStatus().equals(StatusRecordEnum.LEAVE) && recordCourseOld.getIsDeductHouse().equals(1) && recordCourseOld.getIsDeductMoney().equals(0)) {
                    this.recordCourseChangeArrice(recordCourseOld.getId(), StatusRecordEnum.REACH, reachTypeEnum);
                } else {
                    UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
                    recordCourseUpdateWrapper.eq("scheduling_detail_id", courseSchedulingDetailId);
                    recordCourseUpdateWrapper.eq("student_id", studentId);
                    //签退不需要修改这些信息
                    recordCourse.setTeacherId(null);
                    recordCourse.setOldTeacherId(null);
                    recordCourse.setTeacherName(null);
                    recordCourse.setOldGradeId(null);
                    recordCourse.setGradeId(null);
                    recordCourse.setGradeName(null);
                    this.update(recordCourse, recordCourseUpdateWrapper);
                }
            }
        } else {
            //当前时间在开始上课时间之后，设置为请假
            if (recordCourse.getStartDateTime() != null) {
                RecordCourse recordCourseTry = null;
                if (recordCourse.getLessonNum() != null && recordCourse.getLessonNum().equals(1)) {
                    this.getTryLingOne(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getLessonType(), 8);
                    this.deleteTryLing(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getLessonType(), 8);
                }
                if (dateTimeNow.isAfter(recordCourse.getStartDateTime())) {
                    if (recordCourseTry != null) {
                        recordCourse.setReachType(ReachTypeEnum.NORMAL);
                    } else {
                        recordCourse.setReachType(ReachTypeEnum.LATE);
                    }
                } else {
                    recordCourse.setReachType(ReachTypeEnum.NORMAL);
                }
            } else {
                if (reachTypeEnum != null) {
                    recordCourse.setReachType(reachTypeEnum);
                } else {
                    recordCourse.setReachType(ReachTypeEnum.NORMAL);
                }
            }
            this.save(recordCourse);
        }


        return recordCourse.getId();
    }

    public RecordCourse getTryLingOne(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId, Integer lessonType, Integer courseType) {
        RecordCourse recordCourseOld = null;
        try {
            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            recordCourseQueryWrapper.eq("year_part", yearPart);
            recordCourseQueryWrapper.eq("quarter", quarterNum);
            recordCourseQueryWrapper.eq("subjects_id", subjectsId);
            recordCourseQueryWrapper.eq("course_type", courseType);
            recordCourseQueryWrapper.eq("lesson_type", lessonType);
            recordCourseQueryWrapper.eq("student_id", studentId);
            recordCourseQueryWrapper.last("limit 1");
            recordCourseOld = this.getOne(recordCourseQueryWrapper);
        } catch (Exception e) {

        }
        return recordCourseOld;
    }

    public void deleteTryLing(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId, Integer lessonType, Integer courseType) {

        try {
            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            recordCourseQueryWrapper.eq("year_part", yearPart);
            recordCourseQueryWrapper.eq("quarter", quarterNum);
            recordCourseQueryWrapper.eq("subjects_id", subjectsId);
            recordCourseQueryWrapper.eq("course_type", 8);
            recordCourseQueryWrapper.eq("lesson_type", 1);
            recordCourseQueryWrapper.eq("student_id", studentId);
            recordCourseQueryWrapper.ne("is_deduct_house", 1);
            this.remove(recordCourseQueryWrapper);
        } catch (Exception e) {

        }
    }


    /**
     * 补课到课，前添加数据
     *
     * @param courseSchedulingDetailId
     * @param studentId
     * @param studentName
     * @param type
     * @param courseType
     * @return
     */
    public RecordCourse addRecourseBefor(Long courseSchedulingDetailId, Long studentId, String studentName, Integer type, Integer courseType) {
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("scheduling_detail_id", courseSchedulingDetailId);
        recordCourseQueryWrapper.eq("student_id", studentId);
        recordCourseQueryWrapper.last("limit 1");
        RecordCourse recordCourse = recordCourseMapper.selectOne(recordCourseQueryWrapper);
        if (recordCourse != null) {
            return recordCourse;
        } else {
            recordCourse = new RecordCourse();
        }

        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(courseSchedulingDetailId);
        if (courseSchedulingDetailInfo == null) {
            courseSchedulingDetailInfo = new CourseSchedulingDetail();
        }

        Long recordCourseId = null;
        //补课学生、调课、消课、缺课补课
        if (courseType.equals(3) || courseType.equals(4) || courseType.equals(5) || courseType.equals(6)) {
            RepairCourse repairCourseInfo = repairCourseMapper.selectById(courseSchedulingDetailId);
            if (repairCourseInfo != null) {
                BeanUtils.copyProperties(repairCourseInfo, courseSchedulingDetailInfo);
                recordCourseId = repairCourseInfo.getRecordCourseId();
            }
        }

        Grade oldGrade = new Grade();//精品课所在班级（按日程排课）
        //精品课所在班级（按日程排课,没有班级，要添加上精品课所在班级）
        StudentGrade studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(null, studentId, courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getLessonType());
        if (studentGrade != null) {
            Grade grade = iGradeService.getById(studentGrade.getGradeId());
            oldGrade.setId(studentGrade.getGradeId());
            if (grade != null) {
                BeanUtils.copyProperties(grade, oldGrade);
            }
        }
        recordCourse.setOldGradeId(oldGrade.getId());
        recordCourse.setOldTeacherId(oldGrade.getTeacherId());
        if (oldGrade.getYearClassId() != null) {
            recordCourse.setYearClassId(oldGrade.getYearClassId().getKey());
        }

        recordCourse.setStudentId(studentId);
        recordCourse.setLessonNum(courseSchedulingDetailInfo.getLessonNum());//课次
        recordCourse.setStudentName(studentName);
        recordCourse.setStatus(StatusRecordEnum.REACH);
        if (courseType.equals(3)) {
            recordCourse.setType(3);
            if (recordCourseId != null) {
                RecordCourse recordCourseOld = recordCourseMapper.selectById(recordCourseId);
                if (recordCourseOld != null) {
                    recordCourseOld.setIsRepair(1);
                    recordCourseMapper.updateById(recordCourseOld);
                }
            }
        } else {
            recordCourse.setType(type);
        }

        recordCourse.setReachType(ReachTypeEnum.NORMAL);
        recordCourse.setCourseType(courseType);
        Student student = studentMapper.selectById(recordCourse.getStudentId());
        recordCourse.setStudentName(student.getName());

        //老师
        recordCourse.setTeacherId(courseSchedulingDetailInfo.getTeacherId());
        Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());
        if (staff == null) {
            //throw new CommonException(ResultCode.TeacerNo);
        }
        //if(staff.getIsTeacher()!=1){
        //throw new CommonException(ResultCode.NotATeacher);
        //}
        recordCourse.setTeacherName(staff.getName());

        recordCourse.setSchedulingDetailId(courseSchedulingDetailInfo.getId());//排课id
        //校区
        recordCourse.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
        Organization organization = iOrganizationService.getById(courseSchedulingDetailInfo.getSchoolId());
        if (organization != null) {
            recordCourse.setSchoolName(organization.getName());
        }
        //班级
        recordCourse.setGradeId(courseSchedulingDetailInfo.getGradeId());
        /*Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());

        if(grade==null){
            //throw new CommonException(ResultCode.CourseSchedulingClassNo);
            //recordCourse.setTeacherGetHouse(grade.getStuDeductHour());//等确定
        }
        Course course = iCourseService.getById(grade.getCourseId());
        if(course==null){
            //throw new CommonException(ResultCode.COURSE_NOT);
        }*/

        Long courseId = null;
        String courseName = "";
        if (courseSchedulingDetailInfo.getGradeId() != null) {
            Course course = iCourseService.getById(courseSchedulingDetailInfo.getGradeId());
            if (course != null) {
                courseId = course.getId();
                courseName = course.getName();
            }
        }

        //年份与月份
        Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());
        recordCourse.setLessonType(courseSchedulingDetailInfo.getLessonType());//课程类型
        recordCourse.setYearAndQuarter(yearAndQuarter);
        recordCourse.setGradeName(courseSchedulingDetailInfo.getGradeName());
        recordCourse.setCourseId(courseId);
        recordCourse.setCourseName(courseName);
        recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
        //recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
        recordCourse.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
        recordCourse.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());
        recordCourse.setStartDateTime(courseSchedulingDetailInfo.getStartDateTime());
        recordCourse.setEndDateTime(courseSchedulingDetailInfo.getEndDateTime());

        //教室
        recordCourse.setClassRoomId(courseSchedulingDetailInfo.getClassRoomId());
        ClassRoom classRoom = iClassRoomService.getById(courseSchedulingDetailInfo.getClassRoomId());
        if (classRoom != null) {
            recordCourse.setClassRoomName(classRoom.getName());
        }
        //科目
        recordCourse.setSubjectsId(courseSchedulingDetailInfo.getSubjectsId());
        Subjects subjects = iSubjectsService.getById(courseSchedulingDetailInfo.getSubjectsId());
        if (subjects != null) {
            recordCourse.setSubjectsName(subjects.getName());
        }
        recordCourse.setYearPart(courseSchedulingDetailInfo.getYearPart());
        recordCourse.setQuarter(courseSchedulingDetailInfo.getQuarter());
        //1精品课（正常排课），3补课，4调课，5消课
        if (courseType.equals(5)) {
            //recordCourse.setBuckleClassHouse(grade.getStuDeductHour());
            //recordCourse.setTeacherGetHouse(grade.getTeaGainHour());
        }
        UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
        recordCourseUpdateWrapper.eq("scheduling_detail_id", courseSchedulingDetailId);
        recordCourseUpdateWrapper.eq("student_id", studentId);
        this.saveOrUpdate(recordCourse, recordCourseUpdateWrapper);
        return recordCourse;
    }


    public IPage<RecordCourse> recordGradeLog(IPage<?> page, QueryWrapper queryWrapper) {
        IPage<RecordCourse> courseSchedulingDetails = recordCourseMapper.recordGradeLog(page, queryWrapper);
        for (RecordCourse recordCourse : courseSchedulingDetails.getRecords()) {
            Integer shouldCount = iStudentGradeService.getGradeStudyCount(recordCourse.getGradeId());
            recordCourse.setShouldCount(shouldCount);
            Integer solidCount = this.getSolidCount(recordCourse.getSchedulingDetailId(), 1);
            recordCourse.setSolidCount(solidCount);
            RecordCourse recordCourseStatistics = recordCourseMapper.getStatistics(recordCourse.getSchedulingDetailId(), 1);
            if (recordCourseStatistics != null) {
                recordCourse.setBuckleClassHouse(recordCourseStatistics.getBuckleClassHouse());
                recordCourse.setBuckleClassMoney(recordCourseStatistics.getBuckleClassMoney());
                recordCourse.setTeacherGetHouse(recordCourseStatistics.getTeacherGetHouse());
                recordCourse.setSchoolDate(recordCourseStatistics.getSchoolDate());
            }
        }
        return courseSchedulingDetails;
    }


    public List<RecordCourse> getlist(Long schedulingDetailId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheduling_detail_id", schedulingDetailId);
        List<RecordCourse> recordCourseList = recordCourseMapper.getRecordCourseList(queryWrapper);
        return recordCourseList;
    }

    /**
     * 获取实到人数
     *
     * @param schedulingDetailId
     * @return
     */
    public Integer getSolidCount(Long schedulingDetailId, Integer status) {
        QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheduling_detail_id", schedulingDetailId);
        queryWrapper.eq("status", status);
        Long solidCount = recordCourseMapper.selectCount(queryWrapper);
        return Integer.valueOf(solidCount.toString());
    }


    public IPage<StudentClassLogRep> studentClassLog(IPage<RecordCourse> page, Wrapper wrapper) {

        IPage<StudentClassLogRep> studentClassLogRepIPage = recordCourseMapper.studentClassLog(page, wrapper);
        for (StudentClassLogRep studentClassLogRep : studentClassLogRepIPage.getRecords()) {
            if (studentClassLogRep.getStatus().equals(StatusRecordEnum.LEAVE)) {
                Long studentId = studentClassLogRep.getStudentId();
                RepairCourse repairCourse = repairCourseMapper.selectById(studentClassLogRep.getRepairId());
                studentClassLogRep.setLeaveTimes(recordCourseMapper.countLeave(studentId, studentClassLogRep.getGradeId()));
                studentClassLogRep.setMakeUpTimes(recordCourseMapper.countMakeUp(studentId, studentClassLogRep.getGradeId()));
                if (repairCourse != null) {
                    if (studentClassLogRep.getIsRepair() != 1 && repairCourse.getEndDateTime().isBefore(LocalDateTime.now())) {
                        studentClassLogRep.setRepairDate(null);
                        studentClassLogRep.setIsRepair(0);
                    } else {
                        studentClassLogRep.setRepairDate(repairCourse.getEndDateTime());
                        if (repairCourse.getStartDateTime() != null && repairCourse.getEndDateTime() != null) {
                            String startDateR = repairCourse.getStartDateTime().toString();
                            startDateR = startDateR.substring(startDateR.length() - 5);
                            //System.out.println("startDateR:"+startDateR);
                            String endDateR = repairCourse.getEndDateTime().toString();
                            endDateR = endDateR.substring(endDateR.length() - 5);
                            studentClassLogRep.setRepairDateStr(repairCourse.getSchoolDate() + " " + startDateR + "-" + endDateR);
                        }
                    }
                    if (repairCourse.getStartDateTime() != null && repairCourse.getEndDateTime() != null) {
                        String startDateR = repairCourse.getStartDateTime().toString();
                        startDateR = startDateR.substring(startDateR.length() - 5);
                        //System.out.println("startDateR:"+startDateR);
                        String endDateR = repairCourse.getEndDateTime().toString();
                        endDateR = endDateR.substring(endDateR.length() - 5);
                        studentClassLogRep.setPassRepairDateStr(repairCourse.getSchoolDate() + " " + startDateR + "-" + endDateR);
                    }

                    studentClassLogRep.setRepairGradeName(repairCourse.getGradeName());
                    studentClassLogRep.setRepairTeacherName(repairCourse.getTeacherName());
                }
            }
            /*if(studentClassLogRep.getRepairDate() !=null && studentClassLogRep.getIsRepair() == 2 && studentClassLogRep.getRepairDate().isBefore(LocalDateTime.now())) {
                RecordCourse recordCourse = recordCourseMapper.select(studentClassLogRep.getId());
                recordCourse.setIsRepair(0);
                recordCourse.setRepairEndDateTime(null);
                recordCourseMapper.updateById(recordCourse);
            }*/
        }

        return studentClassLogRepIPage;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Boolean deleteForId(Long id) {

        RecordCourse recordCourse = recordCourseMapper.selectById(id);
        if (recordCourse == null) {
            return false;
        }
        if (recordCourse.getIsRepair().equals(1)) {
            return false;
        }

        if (recordCourse.getCourseType().equals(3) || recordCourse.getCourseType().equals(6) || (recordCourse.getCourseType().equals(1) && !recordCourse.getByRecordId().equals(0L))) {
            return this.deleteMakeUpLessons(recordCourse);
        }

        //缺课未补课的
        if (recordCourse.getStatus() == StatusRecordEnum.LEAVE && recordCourse.getIsRepair() != 1) {
            //并已扣课时
            if (recordCourse.getIsDeductHouse().equals(1)) {
                OrderDetail orderDetail = iOrderDetailService.getById(recordCourse.getOrderDetailId());
                if (orderDetail != null) {
                    orderDetail.setUseCourseCount(orderDetail.getUseCourseCount() - recordCourse.getBuckleClassHouse());
                    orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + recordCourse.getBuckleClassHouse());
                    //已扣金额
                    if (recordCourse.getIsDeductMoney().equals(1)) {
                        //由于缺课的未扣金额，这里不需要恢复金额，注释掉
                        BigDecimal userPrice = orderDetail.getUsePrice().subtract(recordCourse.getBuckleClassMoney());
                        if (userPrice.compareTo(BigDecimal.ZERO) < 0) {
                            userPrice = new BigDecimal(0);
                        }
                        orderDetail.setUsePrice(userPrice);
                        BigDecimal residuePrice = orderDetail.getResiduePrice().add(recordCourse.getBuckleClassMoney());
                        if (residuePrice.compareTo(orderDetail.getSolidPrice()) > 0) {
                            residuePrice = orderDetail.getSolidPrice();
                        }
                        orderDetail.setResiduePrice(residuePrice);
                    }
                    iOrderDetailService.updateById(orderDetail);
                    if (recordCourse.getIsDeductHouse() == 1) {
                        StudentGrade studentGrade = iStudentGradeService.getById(recordCourse.getStudentGradeId());
                        if (studentGrade != null) {
                            Integer useCourseCount = studentGrade.getUseCourseCount() - recordCourse.getBuckleClassHouse();//使用课时
                            studentGrade.setUseCourseCount(useCourseCount);
                            if (studentGrade.getReadingStatus().getKey().equals(5) || studentGrade.getReadingStatus().getKey().equals(6)) {
                                studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
                            }
                            iStudentGradeService.updateById(studentGrade);
                        } else {
                            /**
                             * 以下是暂时的
                             */
                            //更新分班里使用的课时
                            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                            studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                            studentGradeQueryWrapper.eq("status", 1);
                            studentGradeQueryWrapper.eq("deleted", 0);
                            studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                            //studentGradeQueryWrapper.eq("reading_status",1);
                            studentGradeQueryWrapper.eq("grade_id", recordCourse.getGradeId());
                            studentGradeQueryWrapper.last("limit 1");
                            studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                            if (studentGrade == null) {
                                studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(recordCourse.getSchoolId(), orderDetail.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType());
                            }
                            if (studentGrade != null) {
                                Integer useCourseCount = studentGrade.getUseCourseCount() - recordCourse.getBuckleClassHouse();//使用课时
                                studentGrade.setUseCourseCount(useCourseCount);
                                if (studentGrade.getReadingStatus().getKey().equals(5) || studentGrade.getReadingStatus().getKey().equals(6)) {
                                    studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
                                }
                                iStudentGradeService.updateById(studentGrade);
                            }
                        }
                    }
                    //isDelete = true;
                }
                iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourse.getId()));
            }

            // 由于前面已经判断过请假已补课、请假已安排补课的无法删除，所以这里没有判断，如果前面的判断删掉了这里需要补上
            QueryWrapper studentLeaveWrapper = new QueryWrapper<>();
            studentLeaveWrapper.eq("student_id",recordCourse.getStudentId());
            studentLeaveWrapper.eq("scheduling_detail_id",recordCourse.getSchedulingDetailId());
            iStudentLeaveApplyService.remove(studentLeaveWrapper);

        } else {
            QueryWrapper<RecordCost> recordCostQueryWrapper = new QueryWrapper<>();
            recordCostQueryWrapper.eq("record_course_id", id);
            List<RecordCost> recordCostList = iRecordCostService.list(recordCostQueryWrapper);
            boolean isDelete = false;
            int delCount = 0;
            for (RecordCost recordCost : recordCostList) {
                OrderDetail orderDetail = iOrderDetailService.getById(recordCost.getOrderDetailId());
                if (orderDetail != null) {
                    orderDetail.setUseCourseCount(orderDetail.getUseCourseCount() - recordCost.getBuckleClassHouse());
                    orderDetail.setResidueCourseCount(orderDetail.getResidueCourseCount() + recordCost.getBuckleClassHouse());

                    BigDecimal userPrice = orderDetail.getUsePrice().subtract(recordCost.getBuckleClassMoney());
                    if (userPrice.compareTo(BigDecimal.ZERO) < 0) {
                        userPrice = new BigDecimal(0);
                    }
                    orderDetail.setUsePrice(userPrice);

                    BigDecimal residuePrice = orderDetail.getResiduePrice().add(recordCost.getBuckleClassMoney());
                    if (residuePrice.compareTo(orderDetail.getSolidPrice()) > 0) {
                        residuePrice = orderDetail.getSolidPrice();
                    }
                    orderDetail.setResiduePrice(residuePrice);
                    iOrderDetailService.updateById(orderDetail);

                    StudentGrade studentGrade = iStudentGradeService.getById(recordCourse.getStudentGradeId());
                    if (studentGrade != null) {
                        Integer useCourseCount = studentGrade.getUseCourseCount() - recordCost.getBuckleClassHouse();//使用课时
                        studentGrade.setUseCourseCount(useCourseCount);
                        if (studentGrade.getReadingStatus().getKey().equals(5) || studentGrade.getReadingStatus().getKey().equals(6)) {
                            studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
                        }
                        iStudentGradeService.updateById(studentGrade);
                    } else {
                        /**
                         * 以下是暂时的
                         */
                        //更新分班里使用的课时
                        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                        studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                        studentGradeQueryWrapper.eq("status", 1);
                        studentGradeQueryWrapper.eq("deleted", 0);
                        studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                        //studentGradeQueryWrapper.eq("reading_status",1);
                        studentGradeQueryWrapper.eq("grade_id", recordCourse.getGradeId());
                        studentGradeQueryWrapper.last("limit 1");
                        studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                        if (studentGrade == null) {
                            studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(recordCourse.getSchoolId(), orderDetail.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType());
                        }
                        if (studentGrade != null) {
                            Integer useCourseCount = studentGrade.getUseCourseCount() - recordCost.getBuckleClassHouse();//使用课时
                            studentGrade.setUseCourseCount(useCourseCount);
                            if (studentGrade.getReadingStatus().getKey().equals(5) || studentGrade.getReadingStatus().getKey().equals(6)) {
                                studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
                            }
                            iStudentGradeService.updateById(studentGrade);
                        }
                    }
                    isDelete = true;
                }
                iRecordCostService.removeById(recordCost.getId());
            }
        }

        /**
         *
         */
        RepairCourse repairCourse = repairCourseMapper.selectById(recordCourse.getSchedulingDetailId());

        if (recordCourse.getCourseType().equals(6)) {
            LackCourseLog lackCourseLog = iLackCourseLogService.getById(repairCourse.getRecordCourseId());
            if (lackCourseLog != null) {
                lackCourseLog.setStatus(0);
                lackCourseLog.setIsSignIn(0);
                lackCourseLog.setIsRepair(0);
                iLackCourseLogService.updateById(lackCourseLog);
            }
        }
        if (repairCourse != null) {
            repairCourseMapper.deleteById(repairCourse.getId());
        }


        //if (isDelete){
        //    delCount = recordCourseMapper.deleteById(id);
        //}
        recordCourse.setDeletedAt(LocalDateTime.now().withNano(0));
        recordCourseMapper.updateById(recordCourse);//更新删除时间
        recordCourseMapper.deleteById(id);
        iRecordCourseLackService.removeById(id);

        return true;
    }

    /**
     * 删除补课类型的记上课
     *
     * @param recordCourse
     * @return
     */
    public boolean deleteMakeUpLessons(RecordCourse recordCourse) {
        RecordCourse recordCourseLack = null;
        OrderDetail orderDetail = iOrderDetailService.getById(recordCourse.getOrderDetailId());
        if (recordCourse.getIsDeductHouse().equals(0)) {
            this.removeById(recordCourse);
            return true;
        }
        if (orderDetail == null) {
            return false;
        }
        if (recordCourse.getIsDeductHouse().equals(1)) {
            if ((recordCourse.getCourseType().equals(1) || recordCourse.getCourseType().equals(3)) && !recordCourse.getByRecordId().equals(0L)) {
                //超过15课次排课补课
                recordCourseLack = this.getById(recordCourse.getByRecordId());
                if (recordCourseLack != null) {
                    recordCourseLack.setIsDeductHouse(1);
                    recordCourseLack.setIsDeductMoney(0);
                    recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
                    recordCourseLack.setBuckleClassMoney(BigDecimal.ZERO);
                    recordCourseLack.setTeacherGetHouse(0);
                    recordCourseLack.setTeacherGetMoney(BigDecimal.ZERO);
                    recordCourseLack.setIsRepair(0);
                    recordCourseMapper.updateById(recordCourseLack);

                    BigDecimal residuePrice = orderDetail.getResiduePrice().add(recordCourse.getBuckleClassMoney());
                    orderDetail.setResiduePrice(residuePrice);
                    BigDecimal usePrice = orderDetail.getUsePrice().subtract(recordCourse.getBuckleClassMoney());
                    orderDetail.setUsePrice(usePrice);
                    iOrderDetailService.updateById(orderDetail);
                }
            } else {
                //QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
                //repairCourseQueryWrapper.eq("scheduling_detail_id",recordCourse.getRepairId());
                RepairCourse repairCourse = repairCourseMapper.selectById(recordCourse.getSchedulingDetailId());
                if (repairCourse != null) {
                    if (recordCourse.getCourseType().equals(3)) {
                        //请假补课
                        recordCourseLack = this.getById(repairCourse.getRecordCourseId());
                        if (recordCourseLack != null) {
                            recordCourseLack.setIsDeductHouse(1);
                            recordCourseLack.setIsDeductMoney(0);
                            recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
                            recordCourseLack.setBuckleClassMoney(BigDecimal.ZERO);
                            recordCourseLack.setTeacherGetHouse(0);
                            recordCourseLack.setTeacherGetMoney(BigDecimal.ZERO);
                            recordCourseLack.setIsRepair(0);
                            recordCourseMapper.updateById(recordCourseLack);


                            BigDecimal residuePrice = orderDetail.getResiduePrice().add(recordCourse.getBuckleClassMoney());
                            orderDetail.setResiduePrice(residuePrice);
                            BigDecimal usePrice = orderDetail.getUsePrice().subtract(recordCourse.getBuckleClassMoney());
                            orderDetail.setUsePrice(usePrice);
                            iOrderDetailService.updateById(orderDetail);
                        }
                    } else if (recordCourse.getCourseType().equals(6)) {
                        //缺课补课
                        LackCourseLog lackCourseLog = iLackCourseLogService.getById(repairCourse.getRecordCourseId());
                        if (lackCourseLog != null) {
                            lackCourseLog.setIsRepair(2);
                            iLackCourseLogService.updateById(lackCourseLog);

                            BigDecimal residuePrice = orderDetail.getResiduePrice().add(recordCourse.getBuckleClassMoney());
                            orderDetail.setResiduePrice(residuePrice);
                            BigDecimal usePrice = orderDetail.getUsePrice().subtract(recordCourse.getBuckleClassMoney());
                            orderDetail.setUsePrice(usePrice);

                            Integer residueCourseCount = orderDetail.getResidueCourseCount() + recordCourse.getBuckleClassHouse();
                            orderDetail.setResidueCourseCount(residueCourseCount);
                            Integer useCourseCount = orderDetail.getUseCourseCount() - recordCourse.getBuckleClassHouse();
                            orderDetail.setUseCourseCount(useCourseCount);
                            iOrderDetailService.updateById(orderDetail);

                            //更新分班里使用的课时
                            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                            studentGradeQueryWrapper.eq("order_detail_id", recordCourse.getOrderDetailId());
                            studentGradeQueryWrapper.eq("status", 1);
                            studentGradeQueryWrapper.eq("deleted", 0);
                            studentGradeQueryWrapper.eq("lesson_type", recordCourse.getLessonType());
                            //studentGradeQueryWrapper.eq("reading_status",1);
                            studentGradeQueryWrapper.eq("grade_id", recordCourse.getGradeId());
                            studentGradeQueryWrapper.last("limit 1");
                            StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                            if (studentGrade == null) {
                                studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(recordCourse.getSchoolId(), orderDetail.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType());
                            }
                            if (studentGrade != null) {
                                Integer gradeUseCourseCount = studentGrade.getUseCourseCount() - recordCourse.getBuckleClassHouse();//使用课时
                                studentGrade.setUseCourseCount(gradeUseCourseCount);
                                if (studentGrade.getReadingStatus().getKey().equals(5) || studentGrade.getReadingStatus().getKey().equals(6)) {
                                    studentGrade.setReadingStatus(ReadingStatusEnum.IN_READING);
                                }
                                iStudentGradeService.updateById(studentGrade);
                            }
                        }
                    }
                }
            }
        } else {
            if (recordCourse.getCourseType().equals(6)) {
                RepairCourse repairCourse = repairCourseMapper.selectById(recordCourse.getSchedulingDetailId());
                //缺课补课
                LackCourseLog lackCourseLog = iLackCourseLogService.getById(repairCourse.getRecordCourseId());
                if (lackCourseLog != null) {
                    lackCourseLog.setIsRepair(2);
                    recordCourseMapper.updateById(recordCourseLack);
                }
            }
        }
        this.removeById(recordCourse);
        return true;
    }


    public IPage<RecordCourse> hourStatistics(IPage<?> iPage, QueryWrapper queryWrapper) {
        IPage<RecordCourse> recordCourseIPage = recordCourseMapper.sumRecordCourse(iPage, queryWrapper);
        return recordCourseIPage;
    }

    public IPage<RecordCourse> hourStudentStatistics(IPage<?> iPage, QueryWrapper queryWrapper) {
        IPage<RecordCourse> recordCourseIPage = recordCourseMapper.sumStudentRecordCourse(iPage, queryWrapper);
        return recordCourseIPage;
    }

    /**
     * 请假学生改为到课
     *
     * @param recordCourseId 记上课id
     * @return
     */
    @Transactional
    public boolean leaveArrive(Long recordCourseId) {
        //记上课记录
        RecordCourse recordCourseOld = recordCourseMapper.selectById(recordCourseId);
        if (recordCourseOld == null)
            return false;
        if (!recordCourseOld.getStatus().equals(StatusRecordEnum.LEAVE))
            throw new CommonException(ResultCode.NOT_REPAIR_STATUS);
        //获取出按排的补课信息
        RepairCourse repairCourseInfo = repairCourseMapper.selectById(recordCourseOld.getRepairId());
        if (repairCourseInfo == null)
            throw new CommonException(ResultCode.NOT_REPAIR);
        RecordCourse recordCourse = this.addRecourseBefor(repairCourseInfo.getId(), repairCourseInfo.getStudentId(), recordCourseOld.getStudentName(), 1, repairCourseInfo.getCourseType());
        if (recordCourse == null) {
            return false;
        }
        boolean rs;
        if (recordCourse.getCourseType().equals(3)) {
            rs = this.repairBuckleMoney(recordCourseOld.getRepairId());
        } else {
            rs = this.recordActionRepair(recordCourse);
        }
        return rs;
    }


    /**
     * 缺课到课添加上课记录
     *
     * @param lackCourseLogId
     * @return
     */
    @Transactional
    public boolean lackRepairArrive(Long lackCourseLogId) {
        //缺课记上课记录
        LackCourseLog lackCourseLogOld = iLackCourseLogService.getById(lackCourseLogId);
        if (lackCourseLogOld == null)
            return false;
        //获取出按排的补课信息
        RepairCourse repairCourseInfo = repairCourseMapper.selectById(lackCourseLogOld.getRepairId());
        if (repairCourseInfo == null)
            throw new CommonException(ResultCode.NOT_REPAIR);

        RecordCourse recordCourse = this.addRecourseBefor(repairCourseInfo.getId(), repairCourseInfo.getStudentId(), lackCourseLogOld.getStudentName(), 1, repairCourseInfo.getCourseType());

        if (recordCourse == null) {
            return false;
        }
        boolean rs = this.recordActionRepair(recordCourse);
        if (rs) {
            lackCourseLogOld.setIsRepair(1);
            lackCourseLogOld.setIsSignIn(1);
            lackCourseLogOld.setStatus(1);
            lackCourseLogOld.setRemark("手动缺课到课");
            iLackCourseLogService.updateById(lackCourseLogOld);
        }
        return rs;
    }

    /**
     * 记上课由请假改为到课或者旷课
     *
     * @return
     */
    @Override
    @Transactional
    public boolean recordCourseChangeArrice(Long recordCoruseId, StatusRecordEnum statusRecordEnum, ReachTypeEnum reachTypeEnum) {
        RecordCourse recordCourse = recordCourseMapper.selectById(recordCoruseId);
        if (recordCourse.getIsDeductHouse().equals(0)) {
            //未扣课时的，先扣课时
            Boolean rs = true;
            if (recordCourse.getCourseType().equals(1)) {
                rs = this.recordAction(recordCourse);
            } else if (recordCourse.getCourseType().equals(4)) {
                RepairCourse repairCourseInfo = repairCourseMapper.selectById(recordCourse.getSchedulingDetailId());
                if (repairCourseInfo != null) {
                    rs = this.recordActionRepair(recordCourse);
                } else {
                    rs = this.recordAction(recordCourse);
                }
            } else {
                rs = this.recordActionRepair(recordCourse);
            }
            if (rs) {
                recordCourse = recordCourseMapper.selectById(recordCoruseId);

            } else {
                return false;
            }
        }

        RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCoruseId);

        Long orderDetailId = null;
        BigDecimal buckleClassMoney = null;
        if (recordCourseLack != null) {
            orderDetailId = recordCourseLack.getOrderDetailId();
            buckleClassMoney = recordCourseLack.getBuckleClassMoney();
        } else {
            orderDetailId = recordCourse.getOrderDetailId();
            buckleClassMoney = recordCourse.getBuckleClassMoney();
        }
        OrderDetail orderDetail = iOrderDetailService.getById(orderDetailId);
        if (orderDetail.getResiduePrice().compareTo(buckleClassMoney) < 0) {
            buckleClassMoney = orderDetail.getResiduePrice();
        }

        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));
        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));
        iOrderDetailService.updateById(orderDetail);

        recordCourse.setStatus(statusRecordEnum);
        if (statusRecordEnum.equals(StatusRecordEnum.REACH)){
            recordCourse.setUseLeaveNum(0);
        }
        recordCourse.setBuckleClassMoney(buckleClassMoney);
        recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCourse.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
        recordCourse.setIsDeductHouse(1);
        recordCourse.setIsDeductMoney(1);
        recordCourse.setReachType(reachTypeEnum);//手动改为到课，为迟到
        recordCourse.setOrderDetailId(recordCourseLack.getOrderDetailId());
        CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(recordCourse.getSchedulingDetailId());
        if (courseSchedulingDetail == null) {
            RepairCourse repairCourse = repairCourseMapper.selectById(recordCourse.getSchedulingDetailId());
            if (repairCourse != null) {
                recordCourse.setUseLeaveNum(repairCourse.getUseLeaveNum());
            }
        } else {
            recordCourse.setUseLeaveNum(courseSchedulingDetail.getUseLeaveNum());
        }

        recordCourseMapper.updateById(recordCourse);

        QueryWrapper<RecordCost> recordCostUpdateWrapper = new QueryWrapper<>();
        recordCostUpdateWrapper.eq("record_course_id", recordCourse.getId());
        recordCostUpdateWrapper.last("limit 1");
        RecordCost recordCost = iRecordCostService.getOne(recordCostUpdateWrapper);

        //recordCost.setOrderDetailId(recordCourseLack.getOrderDetailId());
        //recordCost.setRecordCourseId(recordCourse.getId());
        recordCost.setBuckleClassMoney(buckleClassMoney);
        recordCost.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCost.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
        iRecordCostService.updateById(recordCost);
        iRecordCourseLackService.removeById(recordCourseLack.getId());

        return true;
    }

    /**
     * 由到课改为请假
     *
     * @param recordCoruseId
     * @return
     */
    public boolean recordCourseChangeLive(Long recordCoruseId) {
        RecordCourse recordCourse = recordCourseMapper.selectById(recordCoruseId);
        RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCourse.getId());
        if (recordCourseLack == null) {
            recordCourseLack = new RecordCourseLack();
        }
        if (recordCourse.getIsDeductHouse().equals(0)) {
            //未扣课时的，先扣课时
            Boolean rs = true;
            if (recordCourse.getCourseType().equals(1)) {
                rs = this.recordAction(recordCourse);
            } else if (recordCourse.getCourseType().equals(4)) {
                RepairCourse repairCourseInfo = repairCourseMapper.selectById(recordCourse.getSchedulingDetailId());
                if (repairCourseInfo != null) {
                    rs = this.recordActionRepair(recordCourse);
                } else {
                    rs = this.recordAction(recordCourse);
                }
            } else {
                rs = this.recordActionRepair(recordCourse);
            }
            if (rs) {
                recordCourse = recordCourseMapper.selectById(recordCoruseId);
            } else {
                return false;
            }
        }

        recordCourseLack.setId(recordCourse.getId());
        recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());

        if (recordCourseLack.getBuckleClassMoney() == null) {
            recordCourseLack.setBuckleClassMoney(recordCourse.getBuckleClassMoney());
        }

        recordCourseLack.setTeacherGetMoney(recordCourse.getTeacherGetMoney());
        recordCourseLack.setTeacherGetHouse(recordCourse.getTeacherGetHouse());
        recordCourseLack.setOrderDetailId(recordCourse.getOrderDetailId());
        iRecordCourseLackService.saveOrUpdate(recordCourseLack);

        recordCourse.setStatus(StatusRecordEnum.LEAVE);
        recordCourse.setReachType(ReachTypeEnum.NORMAL);
        //recordCourse.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCourse.setBuckleClassMoney(new BigDecimal(0));
        recordCourse.setTeacherGetHouse(0);
        recordCourse.setTeacherGetMoney(new BigDecimal(0));
        recordCourse.setIsDeductHouse(1);
        recordCourse.setIsDeductMoney(0);
        recordCourse.setUseLeaveNum(1);//请假次数加1
        //recordCourse.setOrderDetailId(0L);
        recordCourseMapper.updateById(recordCourse);
        QueryWrapper<RecordCost> recordCostUpdateWrapper = new QueryWrapper<>();
        recordCostUpdateWrapper.eq("record_course_id", recordCourse.getId());
        recordCostUpdateWrapper.last("limit 1");
        List<RecordCost> recordCostList = iRecordCostService.list(recordCostUpdateWrapper);
        for (RecordCost recordCost : recordCostList) {
            OrderDetail orderDetail = iOrderDetailService.getById(recordCost.getOrderDetailId());
            orderDetail.setResiduePrice(orderDetail.getResiduePrice().add(recordCost.getBuckleClassMoney()));
            orderDetail.setUsePrice(orderDetail.getUsePrice().subtract(recordCost.getBuckleClassMoney()));
            iOrderDetailService.updateById(orderDetail);
            recordCost.setBuckleClassMoney(new BigDecimal(0));
            recordCost.setTeacherGetHouse(0);
            recordCost.setTeacherGetMoney(new BigDecimal(0));
            iRecordCostService.updateById(recordCost);
        }
        return true;
    }


    /**
     * 多扣一次课时,些接口作废
     *
     * @param recordCourseId
     * @return
     */
    public boolean moreRecordeCourse(Long recordCourseId) {
        RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseId);
        if (recordCourse == null) {
            throw new CommonException(ResultCode.NOTDATA);
        }

        //Grade grade = iGradeService.getById(recordCourse.getGradeId());

        Integer stuDeductHourB = 3;

        Integer yearPartAndQuarter = Integer.parseInt(recordCourse.getYearPart() + "" + recordCourse.getQuarter());

        /**
         * 满15次课未扣课时的
         */
        if (recordCourse.getIsDeductHouse().equals(3)) {
            Integer userClassHouse = stuDeductHourB;

            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(recordCourse.getSchoolId(), recordCourse.getStudentId(), recordCourse.getSubjectsId(), yearPartAndQuarter, recordCourse.getLessonType());
            Long lastOrderDetailId = 0L;

            //设置是否需要改为结课
            ReadingStatusEnum readingStatusEnum = ReadingStatusEnum.IN_READING;
            if (residueCourseCount == userClassHouse) {
                readingStatusEnum = ReadingStatusEnum.FINISH;
            }

            if (residueCourseCount >= userClassHouse) {
                Course course = iCourseService.getById(recordCourse.getCourseId());
                Staff staff = iStaffService.getById(recordCourse.getTeacherId());
                List<OrderDetail> orderDetailList = orderDetailMapper.orderDetailListForSubjects(recordCourse.getSchoolId(), recordCourse.getStudentId(), course.getSubjectsId(), yearPartAndQuarter, recordCourse.getLessonType());

                Integer diffClassHosue = userClassHouse;//还差多少课时

                Integer teaGainHourAll = 0;//老师得课时总课时
                BigDecimal teaGainMoneyAll = new BigDecimal(0);

                BigDecimal buckleClassMoneyAll = new BigDecimal(0);
                BigDecimal buckleClassHourAll = new BigDecimal(0);

                for (OrderDetail orderDetail : orderDetailList) {
                    if (diffClassHosue == 0) {
                        continue;
                    }

                    CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
                    if (coursePricing == null) {
                        //此学生数据异常
                        throw new CommonException(ResultCode.SERVER_ERROR);
                    }

                    RecordCost recordCost = new RecordCost();
                    recordCost.setId(idWorker.nextId());
                    recordCost.setRecordCourseId(recordCourse.getId());
                    recordCost.setOrderDetailId(orderDetail.getId());
                    lastOrderDetailId = orderDetail.getId();
                    /**
                     * 本次使用金额 = 扣课时金额 + 服务费 + 材料费
                     */
                    BigDecimal buckleClassMoneyOther = new BigDecimal("0");

                    //判断是否第一次扣课时,第一次扣课时，把服务费和材料费一起扣了
                            /*if(orderDetail.getUseCourseCount() == 0){
                                recordCost.setServePrice(coursePricing.getServePrice());
                                recordCost.setMaterialsPrice(coursePricing.getMaterialsPrice());
                                buckleClassMoneyAll = buckleClassMoneyAll.add(coursePricing.getServePrice()).add(coursePricing.getMaterialsPrice());
                            }else {
                                recordCost.setServePrice(new BigDecimal(0));
                                recordCost.setMaterialsPrice(new BigDecimal(0));
                            }*/

                    //BigDecimal stuDeductHour =  new BigDecimal(grade.getStuDeductHour());
                    //本次扣多少个课时
                    BigDecimal stuDeductHour = new BigDecimal(0);
                    //本次要扣的课时大于等于剩余课时
                    if (diffClassHosue > orderDetail.getResidueCourseCount()) {
                        stuDeductHour = new BigDecimal(orderDetail.getResidueCourseCount());
                        diffClassHosue = diffClassHosue - orderDetail.getResidueCourseCount();
                    } else {
                        stuDeductHour = new BigDecimal(diffClassHosue);
                        diffClassHosue = 0;
                    }

                    //学生此次扣课时使用金额
                    BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));

                    buckleClassMoneyOther = buckleClassMoneyOther.add(buckleClassMoney);


                    /**
                     * compareTo 反回1 表示大于，0等于，-1小于
                     * 如果此次扣除金额大于剩余金额，则改为使用剩余金额
                     */
                    //缺课未补的金额
                    BigDecimal lackMoney = iRecordCourseLackService.getAllBucklemoneyForOrderDetailId(orderDetail.getId());
                    BigDecimal residuePrice = orderDetail.getResiduePrice().subtract(lackMoney);//剩余金额
                    if (residuePrice.compareTo(BigDecimal.ZERO) < 0)
                        residuePrice = new BigDecimal(0);

                    if (userClassHouse == orderDetail.getResidueCourseCount()) {
                        //使用可是等于剩余课时
                        buckleClassMoney = residuePrice;
                        buckleClassMoneyOther = buckleClassMoney;
                    } else if (buckleClassMoneyOther.compareTo(residuePrice) > 0) {
                        //本次使用金额大于剩余金额
                        buckleClassMoney = residuePrice;
                        buckleClassMoneyOther = buckleClassMoney;
                    }
                    //老师课时获得金额
                    BigDecimal courseInMoney = staff.getCourseInMoney();
                    BigDecimal courseInCount = new BigDecimal(staff.getCourseInCount());
                    if (courseInCount.compareTo(new BigDecimal(0)) <= 0) {
                        throw new CommonException(ResultCode.TeacherHouseError);
                    }

                    //BigDecimal teaGainHour = new BigDecimal(grade.getTeaGainHour());//班级上一节课，老师得课时
                    //BigDecimal teaGainMoney = teaGainHour.divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                    recordCost.setBuckleClassHouse(userClassHouse);
                    recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额

                    recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                    //BigDecimal teaGainMoney = new BigDecimal(userClassHouse).divide(courseInCount, BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                    BigDecimal teaGainMoney = new BigDecimal(0);
                    //镇级
                    if (recordCourse.getSchoolId() != null && recordCourse.getSchoolId().equals(1697088501396127745L)) {
                        teaGainMoney = new BigDecimal(17);
                    } else {
                        teaGainMoney = new BigDecimal(20);
                    }

                    recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额
                    recordCost.setOrderDetailId(orderDetail.getId());

                    recordCourse.setBuckleClassHouse(userClassHouse);
                    recordCourse.setBuckleClassMoney(buckleClassMoney);
                    recordCourse.setTeacherGetHouse(Integer.parseInt(courseInCount.toString()));
                    recordCourse.setTeacherGetMoney(teaGainMoney);
                    recordCourse.setIsDeductHouse(1);
                    recordCourse.setIsDeductMoney(1);
                    recordCourse.setOrderDetailId(orderDetail.getId());


                    //全新订单里的使用课时，剩余课时，剩余金额，使用金额
                    //UpdateWrapper<OrderDetail> orderDetailUpdateWrapper = new UpdateWrapper<>();
                    //OrderDetail orderDetail = iOrderDetailService.getById(orderDetail.get());
                    /**
                     使用课时：use_course_count
                     上课累计使用金额：use_price
                     剩余课时：residue_course_count
                     剩余金额：residue_price
                     */
                    //扣课时
                    //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                    Integer useCourseCountForOrder = orderDetail.getUseCourseCount() + userClassHouse;
                    orderDetail.setUseCourseCount(useCourseCountForOrder);//使用课时
                    orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额

                    Integer residueCourseCountForUse = orderDetail.getResidueCourseCount() - userClassHouse;
                    orderDetail.setResidueCourseCount(residueCourseCountForUse);//剩余课时
                    orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额

                    iOrderDetailService.updateById(orderDetail);

                    //UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
                    //recordCostUpdateWrapper.eq("id",recordCost.getId());
                    UpdateWrapper<RecordCost> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("record_course_id", recordCourse.getId());
                    iRecordCostService.saveOrUpdate(recordCost, updateWrapper);

                    //更新分班里使用的课时
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                    studentGradeQueryWrapper.eq("status", 1);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.eq("reading_status", 1);
                    studentGradeQueryWrapper.last("limit 1");
                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    if (studentGrade == null) {
                        studentGradeQueryWrapper = new QueryWrapper<>();
                        studentGradeQueryWrapper.eq("school_id", recordCourse.getSchoolId());
                        studentGradeQueryWrapper.eq("student_id", orderDetail.getStudentId());
                        studentGradeQueryWrapper.eq("subjects_id", course.getSubjectsId());
                        studentGradeQueryWrapper.ne("status", 2);
                        studentGradeQueryWrapper.ne("year_part", recordCourse.getYearPart());
                        studentGradeQueryWrapper.ne("quarter_num", recordCourse.getQuarter());
                        studentGradeQueryWrapper.eq("deleted", 0);
                        studentGradeQueryWrapper.eq("reading_status", 1);
                        studentGradeQueryWrapper.orderByDesc("created_at");
                        studentGradeQueryWrapper.last("limit 1");
                        studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    }
                    if (studentGrade == null) {
                        studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearPart(), orderDetail.getQuarterNum(), recordCourse.getLessonType());
                    }
                    if (studentGrade != null) {
                        Integer useCourseCount = studentGrade.getUseCourseCount() + userClassHouse;//使用课时
                        studentGrade.setUseCourseCount(useCourseCount);
                        studentGrade.setReadingStatus(readingStatusEnum);
                        iStudentGradeService.updateById(studentGrade);
                        recordCourse.setStudentGradeId(studentGrade.getId());
                    }
                    if (readingStatusEnum.getKey().equals(5)) {
                        studentGradeQueryWrapper = new QueryWrapper<>();
                        studentGradeQueryWrapper.eq("school_id", recordCourse.getSchoolId());
                        studentGradeQueryWrapper.eq("student_id", orderDetail.getStudentId());
                        studentGradeQueryWrapper.eq("subjects_id", course.getSubjectsId());
                        studentGradeQueryWrapper.ne("status", 2);
                        studentGradeQueryWrapper.eq("deleted", 0);
                        studentGradeQueryWrapper.eq("reading_status", 1);
                        studentGradeQueryWrapper.orderByDesc("created_at");
                        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                        for (StudentGrade studentGradeUpdate : studentGradeList) {
                            studentGradeUpdate.setReadingStatus(readingStatusEnum);
                            iStudentGradeService.updateById(studentGradeUpdate);
                        }
                    }
                    recordCourse.setRemark(recordCourse.getRemark() + "，手动调整为消课");
                    this.updateById(recordCourse);
                }
            }
        } else {
            throw new CommonException(ResultCode.STATUSNOT);
        }
        return true;
    }

    /**
     * 获取学生到课状态
     *
     * @param yearPart
     * @param quarterNUm
     * @param studentId
     * @param subjectsId
     * @param lessonNum
     * @return
     */
    public RecordCourse getStudentClassStatus(Integer yearPart, Integer quarterNUm, Long studentId, Long subjectsId, Integer lessonNum) {
        return recordCourseMapper.getStudentClassStatus(yearPart, quarterNUm, studentId, subjectsId, lessonNum);
    }

    @Override
    public List<RepairLesson> getRepairLesson(String schoolId, String yearPart, String quarterNum, String subjectsId, String teacherStr) {
        return recordCourseMapper.getRepairLesson(schoolId, yearPart, quarterNum, subjectsId, teacherStr);
    }

    @Override
    public List<RepairLesson> enrollmentData(String schoolId, String startDate, String endDate, String subjectsId, String type, String teacherStr) {
        return recordCourseMapper.enrollmentData(schoolId, startDate, endDate, subjectsId, type, teacherStr);
    }

    /**
     * 请假未补的数量,不包含请假已扣金额的数据
     *
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param subjectsId
     * @param lessonType
     * @return
     */
    @Override
    public Integer getLackCount(Integer yearPart, Integer quarterNum, Long schoolId, Long studentId, Long subjectsId, Integer lessonType) {
        return recordCourseMapper.getLackCount(yearPart, quarterNum, schoolId, studentId, subjectsId, lessonType);
    }

    @Override
    public Integer getRecordCountArrive(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId) {
        return recordCourseMapper.getRecordCountArrive(yearPart, quarterNum, studentId, subjectsId);
    }

    /**
     * 添加临时上课记录
     *
     * @param faceGetScheduling
     * @return
     */
    @Override
    public Long addTemporaryData(FaceGetScheduling faceGetScheduling, Quarter quarter, Long teacherId, Integer signType, String schoolSiteId) {
        //StudentGrade studentGrade = studentGradeMapper.getLastOne(quarter.getYearPart(),quarter.getNum(),faceGetScheduling.getSubjectsId(),faceGetScheduling.getStudentId(),faceGetScheduling.getLessonType());
        //if (studentGrade == null){
        //    return false;
        //}

        Organization schoolInfo = iOrganizationService.getById(faceGetScheduling.getSchoolId());
        Student student = iStudentService.getById(faceGetScheduling.getStudentId());
        Grade grade = iGradeService.getById(faceGetScheduling.getGradeId());

        //RecordCourse recordCourse = new RecordCourse();
        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        String time = nowDateTime.format(formatter);
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("scheduling_detail_id", faceGetScheduling.getSchedulingDetailId());
        recordCourseQueryWrapper.eq("student_id", faceGetScheduling.getStudentId());
        recordCourseQueryWrapper.last("limit 1");
        RecordCourse recordCourse = this.getOne(recordCourseQueryWrapper);
        if (recordCourse == null) {
            recordCourse = new RecordCourse();
            BeanUtils.copyProperties(faceGetScheduling, recordCourse);
            recordCourse.setStartDateTime(nowDateTime);
            recordCourse.setTimeStart(time);
            Staff staff = iStaffService.getOneById(teacherId);
            recordCourse.setTeacherId(teacherId);
            if (staff != null) {
                recordCourse.setTeacherName(staff.getName());
            }

        } else {
            recordCourse.setEndDateTime(nowDateTime);
            recordCourse.setTimeEnd(time);
        }

        if (schoolInfo != null) {
            recordCourse.setSchoolName(schoolInfo.getName());
        }
        if (student != null) {
            recordCourse.setStudentName(student.getName());
        }
        if (grade != null) {
            recordCourse.setYearClassId(grade.getYearClassId().getKey());
        }
        recordCourse.setSchoolDate(LocalDate.now());
        //recordCourse.setStudentGradeId(studentGrade.getId());
        //recordCourse.setOrderDetailId(studentGrade.getOrderDetailId());
        recordCourse.setQuarter(faceGetScheduling.getQuarterNum());
        recordCourse.setYearAndQuarter(Integer.parseInt(faceGetScheduling.getYearPart() + "" + faceGetScheduling.getQuarterNum()));
        recordCourse.setStatus(StatusRecordEnum.REACH);
        recordCourse.setYearClassId(faceGetScheduling.getYearClassId());

        try {
            //获取精品课最后一次排课
            StudentGrade studentGradeLast = iStudentGradeService.getLastOne(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), 1);
            if (studentGradeLast != null) {
                recordCourse.setOldGradeId(studentGradeLast.getGradeId());
                Grade gradeLast = iGradeService.getById(studentGradeLast.getGradeId());
                if (gradeLast != null) {
                    recordCourse.setOldTeacherId(gradeLast.getTeacherId());
                    recordCourse.setYearClassId(gradeLast.getYearClassId().getKey());
                }
            }
        } catch (Exception e) {
        }
        //log.info("==============================", recordCourse);
        this.saveOrUpdate(recordCourse);
        return recordCourse.getId();
    }

    /**
     * 添加临时上课记录
     *
     * @param faceGetScheduling
     * @return
     */
    @Override
    public boolean addTryListenData(FaceGetScheduling faceGetScheduling, Quarter quarter, Long teacherId) {
        //StudentGrade studentGrade = studentGradeMapper.getLastOne(quarter.getYearPart(),quarter.getNum(),faceGetScheduling.getSubjectsId(),faceGetScheduling.getStudentId(),faceGetScheduling.getLessonType());
        //if (studentGrade == null){
        //    return false;
        //}

        Organization schoolInfo = iOrganizationService.getById(faceGetScheduling.getSchoolId());
        Student student = iStudentService.getById(faceGetScheduling.getStudentId());

        //Grade grade = iGradeService.getById(faceGetScheduling.getGradeId());
        //RecordCourse recordCourse = new RecordCourse();
        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        String time = nowDateTime.format(formatter);
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("scheduling_detail_id", faceGetScheduling.getSchedulingDetailId());
        recordCourseQueryWrapper.eq("student_id", faceGetScheduling.getStudentId());
        recordCourseQueryWrapper.last("limit 1");
        RecordCourse recordCourse = this.getOne(recordCourseQueryWrapper);
        if (recordCourse == null) {
            recordCourse = new RecordCourse();
            BeanUtils.copyProperties(faceGetScheduling, recordCourse);
            recordCourse.setStartDateTime(nowDateTime);
            recordCourse.setTimeStart(time);
            Staff staff = iStaffService.getOneById(teacherId);
            recordCourse.setTeacherId(teacherId);
            recordCourse.setOldTeacherId(teacherId);
            if (staff != null) {
                recordCourse.setTeacherName(staff.getName());
            }

        } else {
            recordCourse.setEndDateTime(nowDateTime);
            recordCourse.setTimeEnd(time);
        }

        if (schoolInfo != null) {
            recordCourse.setSchoolName(schoolInfo.getName());
        }
        if (student != null) {
            recordCourse.setStudentName(student.getName());
        }
        recordCourse.setYearClassId(faceGetScheduling.getYearClassId());
        recordCourse.setSchoolDate(LocalDate.now());
        //recordCourse.setStudentGradeId(studentGrade.getId());
        //recordCourse.setOrderDetailId(studentGrade.getOrderDetailId());
        recordCourse.setQuarter(faceGetScheduling.getQuarterNum());
        recordCourse.setYearAndQuarter(Integer.parseInt(faceGetScheduling.getYearPart() + "" + faceGetScheduling.getQuarterNum()));
        recordCourse.setStatus(StatusRecordEnum.REACH);
        //log.info("==============================", recordCourse);
        this.saveOrUpdate(recordCourse);
        return true;
    }

    /**
     * 获取已请假次数(包含了按排还未上课的)
     *
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param subjectsId
     * @param lessonType
     * @return
     */
    @Override
    public Integer getUseLeaveCount(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId, Integer lessonType) {
        return this.getUseLeaveCount(yearPart, quarterNum, studentId, subjectsId, lessonType);
    }

    @Override
    public Boolean delLeaveRecord(String ids) {
        return recordCourseMapper.delLeaveRecord(ids);
    }

    public List<ArrivalRate> arrivalRate(String schoolId, String SubjectsId, Integer YearPart, Integer QuarterNum, String TeacherName, String StartDate, String EndDate, Integer type, String timeStart, String timeEnd, List<Long> baseSchoolIdList, Integer lessonType, String yearClassId, String trackId, String isTeamDetails, String classify, String trackType, String teamId, String name) {
        String schoolStr = "";
        ////1老师，2校区老师，3校长，4校区
        if (schoolId != "") {
            schoolStr = schoolId;
        } else {
            if (type.equals(2)) {
                //校区老师状态，只能看自己所在校区的数据
                schoolStr = baseSchoolIdList.stream().map(Object::toString).collect(Collectors.joining(","));
            }
        }
        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDate localDateNow = LocalDate.now();
        LocalDate startDate = LocalDate.parse(StartDate);
        LocalDate endDate = LocalDate.parse(EndDate);

        String mixDate = this.mixDateFinal;//添加一个系统上线前的日期
        String startDateLast = mixDate;
        String endDateLast = mixDate;

        List<ArrivalRate> arrivalRateList = null;
        Integer rateType = 1;
        if (startDate.isBefore(localDateNow) && endDate.isBefore(localDateNow)) {
            startDateLast = StartDate;
            endDateLast = EndDate;
            StartDate = mixDate;
            EndDate = mixDate;
        } else if (startDate.isBefore(localDateNow) && endDate.equals(localDateNow)) {
            startDateLast = StartDate;
            endDateLast = localDateNow.minusDays(1).toString();
            StartDate = localDateNow.toString();
        } else if (startDate.isAfter(localDateNow) && endDate.isAfter(localDateNow)) {

        } else if (startDate.equals(localDateNow) && endDate.equals(localDateNow)) {

        }
        if (lessonType.equals(1)) {
            //精品课
            if (type == 5) {
                arrivalRateList = recordCourseMapper.arrivalRateTeam(YearPart.toString(), QuarterNum.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearClassId, isTeamDetails, classify, trackType, teamId, name);
            } else {
                arrivalRateList = recordCourseMapper.arrivalRate(schoolStr, YearPart.toString(), QuarterNum.toString(), type.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, rateType, lessonType, null, yearClassId, trackId, name);
            }
        } else {
            boolean isHistory = true;//是否历史数据（当天的除外是历史数据）
            if (YearPart.equals(quarterNow.getYearPart()) && QuarterNum.equals(quarterNow.getNum()) && !localDateNow.isAfter(startDate)) {
                isHistory = false;
            }
            //智能课，刷题班
            if (type == 5) {
                arrivalRateList = recordCourseMapper.reachRateTeam(YearPart.toString(), QuarterNum.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearClassId, isTeamDetails, classify, trackType, teamId, name);
            } else {
                arrivalRateList = recordCourseMapper.reachRate(schoolStr, YearPart.toString(), QuarterNum.toString(), type.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, rateType, isHistory, null, yearClassId, name);
            }
        }

        return arrivalRateList;
    }

    /**
     * 迟到率
     *
     * @param schoolIdList
     * @param SubjectsId
     * @param YearPart
     * @param QuarterNum
     * @param TeacherName
     * @param StartDate
     * @param EndDate
     * @param type
     * @param timeStart
     * @param timeEnd
     * @param baseSchoolIdList
     * @param lessonType
     * @return
     */
    @Override
    public List<ArrivalRate> tardinessRate(String[] schoolIdList, String SubjectsId, Integer YearPart, Integer QuarterNum, String TeacherName, String StartDate, String EndDate, Integer type, String timeStart, String timeEnd, List<Long> baseSchoolIdList, Integer lessonType, String schoolId, String yearCalssIdStr, String trackId, String isTeamDetails, String classify, String trackType, String teamId, String name) {
        String schoolStr = "";
        ////1老师，2校区老师，3校长，4校区
        if (schoolIdList.length > 0) {
            schoolStr = StringUtil.join(schoolIdList, ",");
        } else {
            if (type.equals(2)) {
                //校区老师状态，只能看自己所在校区的数据
                schoolStr = baseSchoolIdList.stream().map(Object::toString).collect(Collectors.joining(","));
            }
        }
        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDate localDateNow = LocalDate.now();
        LocalDate startDate = LocalDate.parse(StartDate);
        LocalDate endDate = LocalDate.parse(EndDate);

        String mixDate = this.mixDateFinal;//添加一个系统上线前的日期
        String startDateLast = mixDate;
        String endDateLast = mixDate;

        List<ArrivalRate> arrivalRateList = null;
        Integer rateType = 2;//1到课率，2迟到率
        if (lessonType.equals(1)) {
            if (startDate.isBefore(localDateNow) && endDate.isBefore(localDateNow)) {
                startDateLast = StartDate;
                endDateLast = EndDate;
                StartDate = mixDate;
                EndDate = mixDate;
            } else if (startDate.isBefore(localDateNow) && endDate.equals(localDateNow)) {
                startDateLast = StartDate;
                endDateLast = localDateNow.minusDays(1).toString();
                StartDate = localDateNow.toString();
            } else if (startDate.isAfter(localDateNow) && endDate.isAfter(localDateNow)) {
            } else if (startDate.equals(localDateNow) && endDate.equals(localDateNow)) {
            }
            //精品课
            if (type != 5) {
                arrivalRateList = recordCourseMapper.arrivalRate(schoolStr, YearPart.toString(), QuarterNum.toString(), type.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, rateType, schoolId, yearCalssIdStr, trackId, name);
            } else if (type == 5) {
                arrivalRateList = recordCourseMapper.arrivalRateTeam(YearPart.toString(), QuarterNum.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearCalssIdStr, isTeamDetails, classify, trackType, teamId, name);
            }
            //精品课
        } else {
            boolean isHistory = true;//是否历史数据（当天的除外是历史数据）

            if (YearPart.equals(quarterNow.getYearPart()) && QuarterNum.equals(quarterNow.getNum()) && !localDateNow.isAfter(startDate)) {
                isHistory = false;
            }
            //智能课，刷题班
            //arrivalRateList = recordCourseMapper.reachRate(schoolStr, YearPart.toString(), QuarterNum.toString(), type.toString(), SubjectsId, StartDate, EndDate, timeStart, timeEnd, lessonType, rateType, isHistory, schoolId,yearCalssIdStr);
        }

        return arrivalRateList;
    }

    @Override
    public IPage<ClassesNum> classesNumList(IPage<ClassesNum> page, String yearPart, String quarterNum, String schoolId, String subjectsId, String startDate, String endDate, String teacherId, String type, String isDescOrAsc, String isFieldToSc) {
        return recordCourseMapper.classesNumList(page, yearPart, quarterNum, schoolId, subjectsId, startDate, endDate, teacherId, type, isDescOrAsc, isFieldToSc);
    }

    @Override
    public IPage<ClassesNum> classesNumDetails(IPage<ClassesNum> page, String yearPart, String quarterNum, String schoolId, String subjectsId, String startDate, String endDate, String teacherId) {
        return recordCourseMapper.classesNumDetails(page, yearPart, quarterNum, schoolId, subjectsId, startDate, endDate, teacherId);
    }

    @Override
    public Integer getRecordCourseByDate(Long subjectsId, Long studentId) {
        return recordCourseMapper.getRecordCourseByDate(subjectsId, studentId);
    }

    @Override
    public Boolean updateReach(Integer reachType, Long id) {
        return recordCourseMapper.updateReach(reachType, id);
    }

    @Override
    public RecordCourse getOneForSchedulingDetailId(Long schedulingDetailId, Long studentId) {
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("scheduling_detail_id", schedulingDetailId);
        recordCourseQueryWrapper.eq("student_id", studentId);
        recordCourseQueryWrapper.last("limit 1");
        RecordCourse recordCourse = recordCourseMapper.selectOne(recordCourseQueryWrapper);
        return recordCourse;
    }

    /**
     * 由请假已扣改为请假未扣
     *
     * @param id
     * @return
     */
    @Override
    public Boolean updateSendBackLeave(Long id) {
        RecordCourse recordCourse = recordCourseMapper.selectById(id);

        // 退回金额到订单
        OrderDetail orderDetail = orderDetailMapper.selectById(recordCourse.getOrderDetailId());
        if (orderDetail != null) {
            // 已使用的金额减去退回金额
            orderDetail.setUsePrice(orderDetail.getUsePrice().subtract(recordCourse.getBuckleClassMoney()));
            // 剩余金额加上退回金额
            orderDetail.setResiduePrice(orderDetail.getResiduePrice().add(recordCourse.getBuckleClassMoney()));
            orderDetailMapper.updateById(orderDetail);
        }else {
            return false;
        }

        // 判断【记上课扣课时与费用明细】表是否已经存在记录
        RecordCost recordCost = iRecordCostService.getOne(new QueryWrapper<RecordCost>().eq("record_course_id", id));
        if (recordCost == null) {
            // 添加到【记上课扣课时与费用明细】表中
            RecordCost saveCost = new RecordCost();
            saveCost.setRecordCourseId(id);
            saveCost.setOrderDetailId(recordCourse.getOrderDetailId());
            saveCost.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
            saveCost.setBuckleClassMoney(recordCourse.getBuckleClassMoney());
            saveCost.setTeacherGetHouse(recordCourse.getTeacherGetHouse());
            saveCost.setTeacherGetMoney(recordCourse.getTeacherGetMoney());
            iRecordCostService.save(saveCost);
        }else {
            recordCost.setBuckleClassMoney(recordCourse.getBuckleClassMoney());
            iRecordCostService.updateById(recordCost);
        }

        // 判断【记上课扣课时与费用明细】表是否已经存在记录
        RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(id);
        if (recordCourseLack == null) {
            // 添加到【记上课扣课时与费用明细】表中
            recordCourseLack = new RecordCourseLack();
            recordCourseLack.setId(id);
            recordCourseLack.setOrderDetailId(recordCourse.getOrderDetailId());
            recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
            recordCourseLack.setBuckleClassMoney(recordCourse.getBuckleClassMoney());
            recordCourseLack.setTeacherGetHouse(recordCourse.getTeacherGetHouse());
            recordCourseLack.setTeacherGetMoney(recordCourse.getTeacherGetMoney());
            iRecordCourseLackService.save(recordCourseLack);
        }

        // 调整上课记录的金额和课时
        recordCourse.setBuckleClassMoney(new BigDecimal(0));
        recordCourse.setIsDeductMoney(0);
        recordCourse.setTeacherGetHouse(0);
        recordCourse.setTeacherGetMoney(BigDecimal.ZERO);
        recordCourse.setIsDeductMoney(0);
        recordCourseMapper.updateById(recordCourse);




        return true;
    }

    /**
     * 获取最近三个学期最后一次上课记录
     *
     * @param lessonType
     * @param studentId
     * @return
     */
    @Override
    public RecordCourse getRecordCourseByLastThreeQuarter(Integer yearPart, Integer quarterNum, Integer lessonType, Long studentId, String subjectsId) {

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(yearPart, quarterNum);
        RecordCourse recordCourse = null;
        try {
            if (ObjectUtil.isNotNull(quarter)){
                Long startQuarterId = quarter.getId();
                Long endQuarterId = quarter.getId();

                if (quarter.getId() > 2) {
                    startQuarterId = startQuarterId - 2;
                }
                recordCourse = recordCourseMapper.getRecordCourseByLastThreeQuarter(lessonType, studentId, subjectsId, startQuarterId, endQuarterId);
                if (ObjectUtil.isNotNull(recordCourse) && recordCourse.getOldTeacherId() == null){
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("student_id", studentId);
                    studentGradeQueryWrapper.eq("year_part", recordCourse.getYearPart());
                    studentGradeQueryWrapper.eq("quarter_num", recordCourse.getQuarter());
                    studentGradeQueryWrapper.eq("is_last", 1);
                    studentGradeQueryWrapper.eq("lesson_type", 1);
                    studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                    studentGradeQueryWrapper.last("limit 1");
                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    if (ObjectUtil.isNotNull(studentGrade)){
                        Grade grade = iGradeService.getById(studentGrade.getGradeId());
                        if (ObjectUtil.isNotNull(grade)){
                            recordCourse.setOldGradeId(grade.getTeacherId());
                        }
                    }
                }
            }
        }catch (Exception e){
            SystemErrorLog systemErrorLog = new SystemErrorLog();
            systemErrorLog.setContent(e.getMessage());
            systemErrorLog.setType(2);
            systemErrorLog.setRemark("获取最近三个学期最后一次上课记录");
            iSystemErrorLogService.save(systemErrorLog);
        }

        return recordCourse;
    }

    @Override
    public Integer getMaxTaskLesson(Integer YearPart, Integer QuarterNum, String SubjectsId,Long courseVersionId,Integer categoryId){
        Integer tastMaxLessonNum = 20;
        try {
            if (SubjectsId.equals("2")){
                tastMaxLessonNum = iMathematicsFeignClient.getTaskNowMaxLessonNum(YearPart.toString(),QuarterNum.toString(),SubjectsId,courseVersionId,categoryId);
            }else if (SubjectsId.equals("3")){
                tastMaxLessonNum = iPhysicsFeignClient.getTaskNowMaxLessonNum(YearPart.toString(),QuarterNum.toString(),SubjectsId,courseVersionId,categoryId);
            }
        }catch (Exception e){}
        return tastMaxLessonNum;
    }

    @Override
    public String getYetLessonNumStr(Integer yearPart,
                                     Integer quarterNum,
                                     Long subjectsId,
                                     Integer lessonType,
                                     Long studentId,
                                     String dateTimeNow
    ){
        return recordCourseMapper.getYetLessonNumStr(yearPart,quarterNum,subjectsId,lessonType,studentId,dateTimeNow);
    }


    @Async("onlineAsync")
    @Override
    public void updateIsUpFirst(Integer yearPart, Integer quarterNum){
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("year_part", yearPart);
        recordCourseQueryWrapper.eq("quarter", quarterNum);
        recordCourseQueryWrapper.eq("lesson_type",1);
        recordCourseQueryWrapper.eq("lesson_num",1);
        recordCourseQueryWrapper.eq("course_type",1);
        List<RecordCourse> recordCourseList = recordCourseMapper.selectList(recordCourseQueryWrapper);
        for (RecordCourse recordCourse : recordCourseList){
            try {
                if (recordCourse.getLessonNum() !=null){
                    StudentClassType studentClassType = new StudentClassType();
                    studentClassType.setYearPart(recordCourse.getYearPart());
                    studentClassType.setQuarterNum(recordCourse.getQuarter());
                    studentClassType.setStudentId(recordCourse.getStudentId());
                    studentClassType.setSubjectsId(recordCourse.getSubjectsId());
                    studentClassType.setIsUpFirst(1);
                    iMqPushService.syncIsUpFirst(studentClassType);
                }
            }catch (Exception e){}

        }
    }

}
